DFS + 回溯(backtracking)
public class Solution {
private static int[][] direction = { new int[]{ 1, 0 }, new int[]{ -1, 0 }, new int[]{ 0, 1 }, new int[]{ 0, -1 } };
public bool Exist(char[][] board, string word) {
int m = board.Length;
int n = board[0].Length;
bool[,] visited = new bool[m, n];
for (int r = 0; r < m; r++)
{
for (int c = 0; c < n; c++)
{
if (dfs(m, n, r, c, 0, word, visited, board))
{
return true;
}
}
}
return false;
}
private bool dfs(int m, int n, int r, int c, int curlen, string word, bool[,] visited, char[][] board)
{
if (r < 0 || r >= m || c < 0 || c >= n || board[r][c] != word[curlen] || visited[r, c])
{
return false;
}
if (curlen + 1 == word.Length)
{
return true;
}
visited[r, c] = true;
foreach (int[] delta_xy in direction)
{
if (dfs(m, n, r + delta_xy[0], c + delta_xy[1], curlen + 1, word, visited, board))
{
return true;
}
}
visited[r, c] = false;
return false;
}
}