# 剑指 Offer 12. 矩阵中的路径

[[“a”,”b”,”c”,”e”],
[“s”,”f”,”c”,”s”],
[“a”,”d”,”e”,”e”]]

1 <= board.length <= 200
1 <= board[i].length <= 200

class Solution {
private:
bool DFS(vector<vector<char>> &board, vector<vector<int>> &visited, int x, int y, const string &word, int idx) {

if(idx == word.size() - 1) return true;

visited[x][y] = 1;
int m = board.size(), n = board[0].size();

vector<vector<int>> dirs = {{1, 0}, {-1, 0}, {0, -1}, {0, 1}};
for(int i = 0; i < dirs.size(); ++i) {
int u = x + dirs[i][0], v = y + dirs[i][1];
if(u >= 0 && u < m && v >= 0 && v < n && visited[u][v] == 0 && board[u][v] == word[idx + 1]) {
bool ans = DFS(board, visited, u, v, word, idx + 1);
if(ans) return true;
}
}

visited[x][y] = 0;

return false;
}
public:
bool exist(vector<vector<char>>& board, string word) {
if(word.size() == 0) return true;
int m = board.size(), n = board[0].size();
vector<vector<int>> visited(m, vector<int>(n, 0));
for(int i = 0; i < m; ++i) {
for(int j = 0; j < n; ++j) {
if(board[i][j] == word[0]) {
if(DFS(board, visited, i, j, word, 0)) return true;
}
}
}
return false;
}
};