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
.
思路分析:这题可以用DFS 搜索解决,但是实现当中有几个地方要注意。首先dfs函数需要维护已经访问过的位置标记数组,当前搜索的位置,当前匹配的word里面char的位置。其次,对于边界条件,标记条件的判断有时放在递归调用之前比较方便,有时放在递归调用之后进入递归函数后的开头部分比较方便,这题属于后者,由于要搜索四个方向,搜索在递归调用前不做越界判断,而在进入递归函数后进行判断,如果越界返回false这样更容易实现。第三,应该尝试以棋盘的每个位置为起点进行搜索。第四,当且仅当四个方向搜索全部返回false,当前dfs函数才返回false,并且返回之前要注意恢复现场,这就是程序中第26行到第28行所对应。visited数组传入dfs函数后内容发生过改变,但是每次都恢复现场给还原成了false,因此,换新起点重新搜索是visited数组已经全部为false,不需要初始化。
AC Code
- public class Solution {
- public boolean exist(char[][] board, String word) {
- int m = board.length;
- if(m == 0) {
- if(word.isEmpty()) return true;
- else return false;
- }
- int n = board[0].length;
- char [] wordArray = word.toCharArray();
- int len = wordArray.length;
- boolean [][] visited = new boolean[m][n];
- for(int i = 0; i < m; i++){
- for(int j = 0; j < n; j++){
- if(dfs(board, wordArray, 0, i, j, visited, m, n)) return true;
- }
- }
- return false;
- }
- boolean dfs(char [][] board, char [] wordArray, int curIndex, int i, int j, boolean[][] visited, int m, int n){
- if(curIndex >= wordArray.length) return true;
- if(i < 0 || i >= m || j < 0 || j >= n || visited[i][j] || board[i][j] != wordArray[curIndex]){
- return false;
- }
- curIndex++;
- visited[i][j] = true;
- boolean flag = dfs(board, wordArray, curIndex, i-1, j, visited, m, n) || dfs(board, wordArray, curIndex, i+1, j, visited, m, n) || dfs(board, wordArray, curIndex, i, j-1, visited, m, n) || dfs(board, wordArray, curIndex, i, j+1, visited, m, n);
- visited[i][j] = false;// restore the state
- return flag;
- }
- }