class Solution {
public boolean exist(char[][] board, String word) {
int row = board.length,col = board[0].length;
boolean[][] visited = new boolean[row][col];
for(int i = 0;i < row;i++){
for(int j = 0;j < col;j++){
if(exist(board,visited,i,j,word,0))
return true;
}
}
return false;
}
public boolean exist(char[][] board,boolean[][] visited,int i,int j,String word,int index){
int row = board.length,col = board[0].length;
char target = word.charAt(index);
if(i < 0 || i >= row || j < 0 || j >= col)
return false;
if(visited[i][j] || board[i][j] != target)
return false;
if(index == word.length()-1)
return true;
visited[i][j] = true;
boolean result = exist(board,visited,i-1,j,word,index+1)
|| exist(board,visited,i+1,j,word,index+1)
|| exist(board,visited,i,j-1,word,index+1)
|| exist(board,visited,i,j+1,word,index+1);
visited[i][j] = false;
return result;
}
}
leetcode79. 单词搜索
最新推荐文章于 2024-08-15 23:31:45 发布