题目描述:
DFS,标准的回溯搜索。
class Solution {
public boolean exist(char[][] board, String word) {
int rows = board.length;
int cols = board[0].length;
char[] words = word.toCharArray();
boolean[][] visited = new boolean[rows][cols];
for (int i = 0 ; i < rows; i++) {
for (int j = 0; j < cols; j++) {
if(dfs(board, words, visited, rows, cols, i ,j, 0)) {
return true;
}
}
}
return false;
}
public boolean dfs(char[][] board, char[] words, boolean[][] visited,
int rows, int cols, int row, int col, int index) {
if (index == words.length) {
return true;
}
if (row < 0 || col < 0 || row >= rows || col >= cols
|| board[row][col] != words[index] || visited[row][col]) {
return false;
}
visited[row][col] = true;
boolean res = dfs(board, words, visited, rows, cols, row - 1, col, index + 1)
|| dfs(board, words, visited, rows, cols, row + 1, col, index + 1)
|| dfs(board, words, visited, rows, cols, row, col - 1, index + 1)
|| dfs(board, words, visited, rows, cols, row, col + 1, index + 1);
visited[row][col] = false;
return res;
}
}