Approach
Depth-first search
For Word Search, the implementation follows one branch at a time, making it suitable for components, trees, backtracking, or dependency exploration.
- Define the state carried into one recursive or stack frame.
- Mark or choose the current state before exploring children.
- Combine child results or undo the choice when the branch finishes.
Code notes
- 32 lines of C++ from the credited upstream file 79.cpp.
- The implementation visibly relies on sequence storage.
- 2 loop blocks detected, together with recursive traversal.
Complexity
Count unique states for graph traversal; for backtracking, count the branching factor and maximum depth.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1class Solution {2 public:3 bool exist(vector<vector<char>>& board, string word) {4 for (int i = 0; i < board.size(); ++i)5 for (int j = 0; j < board[0].size(); ++j)6 if (dfs(board, word, i, j, 0))7 return true;8 return false;9 }10 11 private:12 bool dfs(vector<vector<char>>& board, const string& word, int i, int j,13 int s) {14 if (i < 0 || i == board.size() || j < 0 || j == board[0].size())15 return false;16 if (board[i][j] != word[s] || board[i][j] == '*')17 return false;18 if (s == word.length() - 1)19 return true;20 21 const char cache = board[i][j];22 board[i][j] = '*';23 const bool isExist = dfs(board, word, i + 1, j, s + 1) ||24 dfs(board, word, i - 1, j, s + 1) ||25 dfs(board, word, i, j + 1, s + 1) ||26 dfs(board, word, i, j - 1, s + 1);27 board[i][j] = cache;28 29 return isExist;30 }31};32