public class Solution {
public int dx[] = {1,-1,0,0};
public int dy[] = {0,0,1,-1};
public boolean exist(char[][] board, String word) {
int m = board.length , n = board[0].length;
boolean [][] vis = new boolean[m][n];
for(int i=0;i<m;i++)
for(int j=0;j<n;j++)
if(dfs(board,word,vis,i,j,0))
return true;
return false;
}
public boolean dfs(char[][] board, String word, boolean[][] vis,int x,int y,int cnt){
if(cnt==word.length())
return true;
int m = board.length;
int n = board[0].length;
if(x<0 || y<0 || x>=m || y>=n || board[x][y]!=word.charAt(cnt) || vis[x][y]) //看当前位置与当前要匹配的字符串是否相等
return false;
vis[x][y] = true;
boolean flag = false;
for(int i=0;i<4;i++){
int xx = x+dx[i];
int yy = y+dy[i];
if(dfs(board,word,vis,xx,yy,cnt+1))
return true;
}
vis[x][y] = false;
return false;
}
}
class Solution {public: bool exist(vector<vector<char>>& board, string word) { int row = board.size(); if(row==0) return false; int col = board[0].size(); if(col==0) return false; for(int i=0;i<row;i++) for(int j=0;j<col;j++) if(board[i][j] == word[0] && dfs(i,j,word,0,board)) return true; return false; } bool dfs(int row,int col,string &word,int index,vector<vector<char>> &board){ if(index == word.size()-1) return true; char tmp = board[row][col]; board[row][col] = '#'; if(row-1>=0 && board[row-1][col] == word[index+1]) if(dfs(row-1,col,word,index+1,board)) return true; if(row+1 < board.size() && board[row+1][col] == word[index+1]) if(dfs(row+1,col,word,index+1,board)) return true; if(col-1>=0 && board[row][col-1]==word[index+1]) if(dfs(row,col-1,word,index+1,board)) return true; if(col+1<board[0].size() && board[row][col+1] == word[index+1]) if(dfs(row,col+1,word,index+1,board)) return true; board[row][col] = tmp; return false; } };