const int N = 20;
int dx[] = {0, 0, 1, -1};
int dy[] = {1, -1, 0, 0};
class Solution {
public:
bool dfs(int i, int j, int n, int m, vector<vector<char>>& board,
string& word, vector<vector<bool>>& st, int cnt) {
if (board[i][j] != word[cnt])
return false;
if (cnt == word.size()-1)
return true;
st[i][j]=true;
for (int k = 0; k < 4; ++k) {
int x = dx[k] + i, y = dy[k] + j;
if (x < 0 || x >= n || y < 0 || y >= m || st[x][y])
continue;
if (
dfs(x, y, n, m, board, word, st, cnt+1))
return true;
}
st[i][j]=false;
return false;
}
bool exist(vector<vector<char>>& board, string word) {
int n = board.size(), m = board[0].size();
string path;
for (int i = 0; i < n; ++i) {
for (int j = 0; j < m; ++j) {
vector<vector<bool>> st(n, vector<bool>(m, false));
if (board[i][j] == word[0] &&dfs(i, j, n, m, board, word, st, 0))
return true;
}
}
return false;
}
};