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 =
[
['A','B','C','E'],
['S','F','C','S'],
['A','D','E','E']
]
word = "ABCCED"
, -> returns true
,word =
"SEE"
, -> returns true
,word = "ABCB"
, -> returns false
.
思路: flag数组记录已经访问过的数组元素;回溯法。
<span style="font-size:14px;">public class Solution {
public boolean exist(char[][] board, String word) {
int m=board.length,n=board[0].length;
boolean[][] flag=new boolean[m][n];
for(int i=0;i<m;i++){
for(int j=0;j<n;j++){
if(board[i][j]==word.charAt(0)){
if(existHelp(board,flag,i,j,word,0))
return true;
}
}
}
return false;
}
public boolean existHelp(char[][] board,boolean[][] flag,int i,int j,String word,int start){
if(start==word.length())
return true;
boolean res=false;
if(i<0||j<0||i==board.length||j==board[0].length||flag[i][j])
return false;
if(board[i][j]==word.charAt(start)){
flag[i][j]=true;
res=existHelp(board,flag,i-1,j,word,start+1)||existHelp(board,flag,i+1,j,word,start+1)||existHelp(board,flag,i,j-1,word,start+1)||existHelp(board,flag,i,j+1,word,start+1);
flag[i][j]=false;
}
return res;
}
}</span>