[LeetCode] Word Search
A typical DFS problem. Just go ahead...
1 class Solution { 2 public: 3 bool exist(vector<vector<char>>& board, string word) { 4 int m = board.size(), n = board[0].size(); 5 for (int i = 0; i < m; i++) 6 for (int j = 0; j < n; j++) 7 if (search(board, i, j, word.c_str())) 8 return true; 9 return false; 10 } 11 private: 12 bool search(vector<vector<char>>& board, int r, int c, const char* word) { 13 if (!word[0]) return true; 14 int m = board.size(), n = board[0].size(); 15 if (r < 0 || r >= m || c < 0 || c >= n || board[r][c] != word[0]) return false; 16 board[r][c] = '$'; 17 if (search(board, r - 1 ,c, word + 1) || search(board, r + 1, c, word + 1) || 18 search(board, r, c - 1, word + 1) || search(board, r, c + 1, word + 1)) 19 return true; 20 board[r][c] = word[0]; 21 return false; 22 } 23 };