单词搜索
题目:
给定一个二维网格和一个单词,找出该单词是否存在于网格中。
单词必须按照字母顺序,通过相邻的单元格内的字母构成,其中“相邻”单元格是那些水平相邻或垂直相邻的单元格。同一个单元格内的字母不允许被重复使用。
示例:
board =
[
['A','B','C','E'],
['S','F','C','S'],
['A','D','E','E']
]
给定 word = "ABCCED", 返回 true
给定 word = "SEE", 返回 true
给定 word = "ABCB", 返回 false
解题思路:运用DFS对所有结果进行遍历
class Solution {
private static int[][] next = new int[][]{{0, 1}, {1, 0}, {-1, 0}, {0, -1}};
public boolean exist(char[][] board, String word) {
char[] ch = word.toCharArray();
boolean[][] book = new boolean[board.length][board[0].length];
for(int i = 0; i < board.length; i++) {
for(int j = 0; j < board[i].length; j++) {
if(check(board, ch, book, i, j, 0)) {
return true;
}
}
}
return false;
}
private boolean check(char[][] board, char[] ch, boolean[][] book, int i, int j, int cur) {
if(board[i][j] != ch[cur]) {
return false;
} else if(cur >= ch.length - 1) {
return true;
}
book[i][j] = true;
for(int k = 0; k < 4; k++) {
int next_i = i + next[k][0], next_j = j + next[k][1];
if(next_i >= 0 && next_i < board.length && next_j >= 0 && next_j < board[0].length && !book[next_i][next_j]) {
book[next_i][next_j] = true;
if(check(board, ch, book, next_i, next_j, cur + 1)) {
return true;
}
book[next_i][next_j] = false;
}
}
book[i][j] = false;
return false;
}
}