给定一个二维网格和一个单词,找出该单词是否存在于网格中。
单词必须按照字母顺序,通过相邻的单元格内的字母构成,其中“相邻”单元格是那些水平相邻或垂直相邻的单元格。同一个单元格内的字母不允许被重复使用。
示例:
board =
[
['A','B','C','E'],
['S','F','C','S'],
['A','D','E','E']
]
给定 word = "ABCCED", 返回 true.
给定 word = "SEE", 返回 true.
给定 word = "ABCB", 返回 false.
解:一样使用回溯法,不再赘述。board[i][j] = ‘#’;是为了防止递归时字母被重复使用。
public boolean exist(char[][] board, String word) {
for (int i = 0; i < board.length; i++) {
for (int j = 0; j < board[0].length; j++) {
if (exist(board, i, j, word, 0)) {
return true;
}
}
}
return false;
}
private boolean exist(char[][] board, int i, int j, String word, int start) {
if (start >= word.length()) {
return true;
}
if (i < 0 || i >= board.length || j < 0 || j >= board[0].length) {
return false;
}
if (board[i][j] == word.charAt(start++)) {
char c = board[i][j];
board[i][j] = '#';
boolean res =
exist(board, i + 1, j, word, start) ||
exist(board, i - 1, j, word, start) ||
exist(board, i, j + 1, word, start) ||
exist(board, i, j - 1, word, start);
board[i][j] = c;
return res;
}
return false;
}