Given a 2D board and a word, find if the word exists in the grid.
The word can be constructed from letters of sequentially adjacent cell, where "adjacent" cells are those horizontally or vertically neighboring. The same letter cell may not be used more than once.
For example,
Given board =
[ ["ABCE"], ["SFCS"], ["ADEE"] ]word =
"ABCCED"
, -> returns
true
,
word =
"SEE"
, -> returns
true
,
word =
"ABCB"
, -> returns
false
.
对于这种要找出所以可能解的问题,思路就两个字——回溯。
1) 一开始匹配第一个字符,找到所有可能的起始点位置。
2)对于每个位置,分别可以向上下左右四个方向进行深度遍历搜索。
private boolean dfs(char[][] board, String word, int i, int j,
boolean[][] visited) {
// check board[i - 1][j]
if (i - 1 >= 0 && visited[i - 1][j] == false
&& board[i - 1][j] == word.charAt(0)) {
if (word.length() == 1) {
return true;
} else {
visited[i - 1][j] = true;
if (dfs(board, word.substring(1), i - 1, j, visited))
return true;
// backtrack
visited[i - 1][j] = false;
}
}
// check board[i + 1][j]
if (i + 1 < board.length && visited[i + 1][j] == false
&& board[i + 1][j] == word.charAt(0)) {
if (word.length() == 1) {
return true;
} else {
visited[i + 1][j] = true;
if (dfs(board, word.substring(1), i + 1, j, visited))
return true;
// backtrack
visited[i + 1][j] = false;
}
}
// check board[i][j - 1]
if (j - 1 >= 0 && visited[i][j - 1] == false
&& board[i][j - 1] == word.charAt(0)) {
if (word.length() == 1) {
return true;
} else {
visited[i][j - 1] = true;
if (dfs(board, word.substring(1), i, j - 1, visited))
return true;
// backtrack
visited[i][j - 1] = false;
}
}
// check board[i][j + 1]
if (j + 1 < board[0].length && visited[i][j + 1] == false
&& board[i][j + 1] == word.charAt(0)) {
if (word.length() == 1) {
return true;
} else {
visited[i][j + 1] = true;
if (dfs(board, word.substring(1), i, j + 1, visited))
return true;
// backtrack
visited[i][j + 1] = false;
}
}
return false;
}
public boolean exist(char[][] board, String word) {
if (board.length == 0 || word.length() == 0)
return true;
boolean[][] visited = new boolean[board.length][board[0].length];
for (int i = 0; i < board.length; i++) {
for (int j = 0; j < board[0].length; j++) {
if (board[i][j] == word.charAt(0)) {
if (word.length() == 1) {
return true;
} else {
visited[i][j] = true;
if (dfs(board, word.substring(1), i, j, visited))
return true;
// backtrack
visited[i][j] = false;
}
}
}
}
return false;
}
代码写得比较冗余,dfs方法里有很多重复代码,其实可以弄一个数组,把四个方向的位移给写进去,这样代码会更精简。