79. 单词搜索

79. 单词搜索

leetcode 79. 单词搜索


题目:79. 单词搜索

给定一个二维网格和一个单词,找出该单词是否存在于网格中。

单词必须按照字母顺序,通过相邻的单元格内的字母构成,其中“相邻”单元格是那些水平相邻或垂直相邻的单元格。同一个单元格内的字母不允许被重复使用。

示例:

board =
[
[‘A’,’B’,’C’,’E’],
[‘S’,’F’,’C’,’S’],
[‘A’,’D’,’E’,’E’]
]

给定 word = “ABCCED”, 返回 true
给定 word = “SEE”, 返回 true
给定 word = “ABCB”, 返回 false

提示:

  • board 和 word 中只包含大写和小写英文字母。
  • 1 <= board.length <= 200
  • 1 <= board[i].length <= 200
  • 1 <= word.length <= 10^3

方法:Backtracking(回溯)

思路:Backtracking(回溯),用flag标记位置是否被搜索,通过遍历board找到第一个word字母位置开始向4个方向搜索,当搜索到边界或者已被搜索过的位置或者该位置的字母不是word对应位置的字母则回退到上一步,继续搜索其他方向,当word包含的所有字母都被搜索到时,返回true,停止递归回溯。

运行数据:执行用时:8 ms,内存消耗:41.9 MB

复杂度分析:

  • 时间复杂度:O((m * n)^2),m为board行数,n为board的列数,最坏情况时word在二维网格board中蛇形排列,长度等于board的元素个数,此时递归层次为m * n,每次递归会拓展出4中情况,所以递归搜索的时间复杂度为O(4 * m * n) = O(m * n), 在主函数中遍历board,以不同位置为搜索入口时的时间复杂度为O(m * n),所以总时间复杂度为O((m * n)^2)。
  • 空间复杂度:O(m * n),空间消耗主要集中于递归时栈的开销,最坏情况时为O(m * n)。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
// LeetCode指定调用方法 
public boolean exist(char[][] board, String word) {

int m = board.length;
int n = board[0].length;

boolean[][] flag = new boolean[m][n];

for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if(wordSearch(board, word, flag, i, j, 0)) {
return true;
}
}
}
return false;

}

private int[][] direction = {{0, 1}, {0, -1}, {1, 0}, {-1, 0}};

// 在二维网格board中搜索word单词,a、b记录当前搜索位置,t记录当前已搜索到的单词字母数量
private boolean wordSearch(char[][] board, String word, boolean[][] flag, int a, int b, int t) {

// 当单词字母全部被搜索到时,返回true
if (word.length() == t) {
return true;
}

// 当搜索到边界或者已被搜索过的位置或者该位置的字母不是word对应位置的字母时,返回false
if (a < 0 || b < 0 || a >= board.length || b >= board[0].length || flag[a][b] || board[a][b] != word.charAt(t)) {
return false;
}

// 标记已搜索到的位置
flag[a][b] = true;

for (int[] d : direction) {

// 当单词已被搜索完时,不在继续搜索,停止递归回溯
if (wordSearch(board, word, flag, a + d[0], b + d[1], t + 1)) {
return true;
}
}

// 复原标记
flag[a][b] = false;

return false;
}

学习所得,资料、图片部分来源于网络,如有侵权,请联系本人删除。

才疏学浅,若有错误或不当之处,可批评指正,还请见谅!


 
Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×