给定一个二维网格和一个单词,找出该单词是否存在于网格中。
单词必须按照字母顺序,通过相邻的单元格内的字母构成,
其中“相邻”单元格是那些水平相邻或垂直相邻的单元格。
同一个单元格内的字母不允许被重复使用。
示例:
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
通过次数98,101提交次数227,640
public class Main{
public static void main(String[] args) {
char[][] board ={
{'A','B','C','E'},
{'S','F','C','S'},
{'A','D','E','E'}
};
System.out.println(exist(board,"ABCCED"));
}
public static boolean exist(char[][] board, String word) {
int x = board.length, y = board[0].length;
boolean[][] visited = new boolean[x][y];
for (int i = 0; i < x; i++) {
for (int j = 0; j < y; j++) {
if (check(board, visited, i, j, word, 0)) {
return true;
}
}
}
return false;
}
public static boolean check(char[][] board, boolean[][] visited, int x, int y, String s, int k) {
if (board[x][y] != s.charAt(k)) {
return false;
} else if (s.length() - 1 == k) {
return true;
}
visited[x][y] = true;
int[][] lead = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};
for (int num = 0; num < lead.length; num++) {
int tempx = x + lead[num][0];
int tempy = y + lead[num][1];
if (tempx >= 0 && tempx < board.length && tempy >= 0 && tempy < board[0].length) {
if (!visited[tempx][tempy]) {
if (check(board, visited, tempx, tempy, s, k+1)) {
return true;
}
}
}
}
visited[x][y] = false;
return false;
}
}