class Solution {
public:
bool exist(vector<vector<char>>& board, string word) {
int m = board.size();
int n = board[0].size();
vector<vector<bool>> visited(m, vector<bool>(n, false));
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if(search(board, visited, word, i, j, 0)) {
return true;
}
}
}
return false;
}
private:
bool search(vector<vector<char>>& board, vector<vector<bool>>& visited, string word, int row, int col, int index){
if (index == word.length()) {
return true;
}
if (row < 0 || row >= board.size() || col < 0 || col >= board[0].size() || visited[row][col] || board[row][col] != word[index]) {
return false;
}
visited[row][col] = true;
if(search(board, visited, word, row + 1, col, index + 1)) {
return true;
}
if(search(board, visited, word, row - 1, col, index + 1)) {
return true;
}
if(search(board, visited, word, row, col + 1, index + 1)) {
return true;
}
if(search(board, visited, word, row, col - 1, index + 1)) {
return true;
}
visited[row][col] = false;
return false;
}
};