class Solution { public:
int dirX[4] = {0, 1, 0, -1}; int dirY[4] = {1, 0, -1, 0}; 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 (board[i][j] == word[0]) if (find(board, word, j, i, 0)) return 1; } return 0; } bool find(vector<vector<char>> &board, string &word, int x, int y, int pos) { if (pos >= word.size()) return 1; if (x < 0 || x > board[0].size() - 1 || y < 0 || y > board.size() - 1 || board[y][x] != word[pos]) return 0; bool ans = 0; board[y][x] += 128; for (int i = 0; i < 4; i++) { ans = ans || find(board, word, x + dirX[i], y + dirY[i], pos + 1); } board[y][x] -= 128; return ans; }
};
|