【解题思路】
用回溯的方法,查询board[ ][ ]这个二维数组。
class Solution {
public boolean exist(char[][] board, String word) {
int m = board.length;
int n = board[0].length;
boolean[][] visited = new boolean[m][n];
for(int i = 0; i < m; i++)
{
for(int j = 0; j < n; j++)
{
if(DFS(board, word, visited, i, j, 0))
{
return true;
}
}
}
return false;
}
public boolean DFS(char[][] board, String word, boolean[][] visited, int row, int col, int k)
{
if(board[row][col] != word.charAt(k))
{
return false;
}
else if(k == word.length() - 1)
{
return true;
}
visited[row][col] = true;
boolean flag = false;
int[][] directions = {{0,1},{1,0},{0,-1},{-1,0}};
for(int[] dire : directions)
{
int newRow = row + dire[0];
int newCol = col + dire[1];
if(newRow >= 0 && newCol >= 0 && newRow < board.length && newCol < board[0].length)
{
if(!visited[newRow][newCol])
{
flag = DFS(board, word, visited, newRow, newCol, k+1);
if(flag) break;
}
}
}
visited[row][col] = false;
return flag;
}
}