class Solution {
public:
bool backtracking(vector<vector<char>>& board, string& word, int index, int row, int col) {
if(index == word.size()) {
return true;
}
if(row < 0 || row == board.size() || col < 0 || col == board[0].size() || word[index] != board[row][col]) {
return false;
}
board[row][col] = '#';
bool r1 = backtracking(board, word, index + 1, row + 1, col);
bool r2 = backtracking(board, word, index + 1, row - 1, col);
bool r3 = backtracking(board, word, index + 1, row, col + 1);
bool r4 = backtracking(board, word, index + 1, row, col - 1);
board[row][col] = word[index];
return r1 || r2 || r3 || r4;
}
bool exist(vector<vector<char>>& board, string word) {
for(int i = 0; i < board.size(); i++) {
for(int j = 0; j < board[0].size(); j++) {
if(backtracking(board, word, 0, i, j) == true) {
return true;
}
}
}
return false;
}
};