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", -> return true,
word ="SEE", -> return true,
word ="ABCB", -> return false.
解题思路:
- 这题是典型的 DFS 问题,同样需要运用到递归
- 设置一个 visited 数组,用来记录节点是否被访问过
- 从二维数组 0,0 开始递归,如果 word 与 board 相符,则递归调用当前元素上下左右的四个位置,直至 word 长度被返回
代码如下:
// 记录元素是否被访问过
boolean [][] visited = null;
public boolean exist(char[][] board, String word) {
int m = board.length;
int n = board[0].length;
visited = new boolean [m][n];
char [] words = word.toCharArray();
for(int i = 0; i < m; i++){
for(int j = 0; j < n; j++){
// 如果返回为真,就返回 true,否则继续遍历下一个字母
if(search(0,i,j,board,words,visited))
return true;
}
}
return false;
}
// 递归函数,
public boolean search(int index,int i, int j,char [][] board, char [] words,boolean [][] visited ){
// 如果 index 的长度等于 word 的长度,就返回 true
if(index == words.length) return true;
int m = board.length;
int n = board[0].length;
// 这里需要全面的判断 i, j,因为 i,j 在后面会执行 +1, -1 的操作
if(i < 0 || j < 0 || i >= m || j >= n
|| visited[i][j] || board[i][j] != words[index])
return false;
// 将当前的元素设置为已访问
visited[i][j] = true;
// 递归处理该元素的上下左右四个节点
boolean re = search(index + 1,i - 1,j,board,words,visited)
|| search(index + 1,i + 1,j,board,words,visited)
|| search(index + 1,i,j - 1,board,words,visited)
|| search(index + 1,i,j + 1,board,words,visited);
// 递归结束,恢复该元素的状态
visited[i][j] = false;
return re;
}