题目
https://leetcode.com/problems/word-search/
题解
回溯 + DFS,回溯是有后效性的,所以不能转化为 DP
class Solution {
int M;
int N;
public boolean exist(char[][] board, String word) {
M = board.length;
N = board[0].length;
for (int i = 0; i < M; i++) {
for (int j = 0; j < N; j++) {
if (dfs(word, 0, i, j, board, new boolean[M][N])) return true;
}
}
return false;
}
public boolean dfs(String word, int index, int i, int j, char[][] board, boolean[][] visited) {
if (index == word.length()) return true;
if (i < 0 || i == M || j < 0 || j == N || visited[i][j] || board[i][j] != word.charAt(index)) return false;
visited[i][j] = true;
boolean result = dfs(word, index + 1, i + 1, j, board, visited) ||
dfs(word, index + 1, i - 1, j, board, visited) ||
dfs(word, index + 1, i, j + 1, board, visited) ||
dfs(word, index + 1, i, j - 1, board, visited);
visited[i][j] = false;
return result;
}
}