题目:
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.
思路:递归 , 从 board中的任意个点出发匹配word(DFS) , 如果匹配到就返回true,
在每次匹配的过程(DFS)中,设置一个visited数组,记录该节点是否已经访问过;
public static boolean exist(char[][] board, String word) {
int rows = board.length;
if(rows <= 0 || word == null || word.isEmpty()) return false;
int cols = board[0].length;
int len = word.length();
if(rows * cols < len) return false;
// 接下来就是从每个点出发,检查是否可以搜索到符合要求的word
for(int i = 0 ; i < rows ; i++) {
for(int j = 0 ; j < cols ; j++) {
//对于每次检查,需要建立一个矩阵来记录是否访问过
boolean[][] visited = new boolean[rows][cols];
// 假设以board[i][j]匹配word中的第一个字符
if(check(board , word ,visited , 0 , i , j)) {
return true;
}
}
}
return false;
}
private static boolean check(char[][] board, String word ,boolean[][] visited, int targetIdx, int bRow,
int bCol) {
// 已匹配所有字符
// 递归出口
if(targetIdx >= word.length()) return true;
if(bRow >= board.length || bCol >= board[0].length) return false;
if(bRow < 0 || bCol < 0) return false;
if(visited[bRow][bCol])
return false;
if(!(board[bRow][bCol] == word.charAt(targetIdx)))
return false;
visited[bRow][bCol] = true;
boolean up = check(board , word, visited , targetIdx + 1 , bRow - 1 , bCol);
boolean down = check(board , word, visited , targetIdx + 1 , bRow + 1 , bCol);
boolean left = check(board , word, visited , targetIdx + 1 , bRow , bCol - 1);
boolean right = check(board , word, visited , targetIdx + 1 , bRow , bCol + 1);
if(up || down || left || right) {
return true;
}
// 否则 则表示该节点不能匹配从tartetIdx以后的部分,所以应当将它的vistied = false
visited[bRow][bCol] = false;
return false;
}