单词搜索

问题陈述

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

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

示例:

1
2
3
4
5
6
7
8
9
10
board =
[
['A','B','C','E'],
['S','F','C','S'],
['A','D','E','E']
]

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

代码实现

DFS

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
class Solution {
//用于标记是否已经找到了解
private boolean flag;

public boolean exist(char[][] board, String word) {
if(board == null || board.length == 0 || board[0].length == 0 ) {
return false;
}
for(int i = 0; i < board.length; i++) {
for(int j = 0; j < board[0].length; j++) {
if(dfs(board, i, j, word, 0)) {
return true;
}
}
}
return false;
}

private boolean dfs(char[][] board, int i, int j, String word, int cur) {
if(cur == word.length()) {
flag = true;
return true;
}
if(i < 0 || i >= board.length || j < 0 || j >= board[0].length
|| board[i][j] != word.charAt(cur)) {
return false;
}
//如果没有找到解,则继续DFS
if(!flag) {
char c = board[i][j];
board[i][j] = '.';
boolean ret1 = dfs(board, i + 1, j, word, cur + 1);
boolean ret2 = dfs(board, i - 1, j, word, cur + 1);
boolean ret3 = dfs(board, i, j + 1, word, cur + 1);
boolean ret4 = dfs(board, i, j - 1, word, cur + 1);
board[i][j] = c;
return ret1 || ret2 || ret3 || ret4;
}else {
//找到解了,直接结束DFS并返回,这就是剪枝
return true;
}
}
}


附:一.System.arraycopy(两数组合并)使用的基本定义
public static void arraycopy(Object src, int srcPos, Object dest, int destPos, int length)

src:源数组;

srcPos:源数组要复制的起始位置;

dest:目的数组;

destPos:目的数组放置的起始位置;

length:复制的长度.
————————————————

回溯

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
public class Solution{
private static final int[][] direction={{1,0},{-1,0},{0,1},{0,-1}};
private int m;
private int n;
//主函数
public boolean isExit(char[][] board,String word){
if(word==null||word.length()==0){
return false;
}
if(board==null||board.length==0||board[0].length==0){
return false;
}
m=board.length;
n=board[0].length;
boolean[][] visited=new boolean[m][n];
for(int r=0;r<m;r++){
for(int c=0;c<n;c++){

}
}
}
//回溯
private boolean backtracking(int curLen, int r, int c, boolean[][] visited, char[][] board, String word){
//base case
if(curLen==word.length()){
return true;
}
if(r<0 || r>m || c<0 || c>n || visited[r][c] || board[r][c]!=word.charAt(curLen)){
return false;
}
visited[r][c]=true;
//选择
for(int[] d:direction){
if(backtracking(curLen+1,r+d[0],r+d[1],visited,board,word)){
return true;
}
}
//撤销
visited[r][c]=false;
return false;
}
}