← Home

79. Word Search

LeetCode article · C++ solution
Website made by wuisabel-gif · Original C++ code by keineahnung2345
graph traversalC++Markdown
79

I like to read this solution as a small machine: keep the useful information, throw away the noise. For 79. Word Search, the solution in this repository is mainly a graph traversal solution.

Guide

What?

The first job is to translate the English prompt into state, transition, and stopping conditions. Instead of trying to be clever immediately, read the code as a sequence of questions:

  • What state are we keeping?
  • How do we move from one state to the next?
  • When do we know the answer is already determined?

For this file, the main tools are: graph traversal.

The notes already sitting in the source point us in the right direction:

  • dfs

Guide

When?

This pattern shows up when the brute force version has too many repeated checks, too many possible branches, or too much bookkeeping to do by hand. The accepted code reduces that pressure by storing exactly the information that remains useful later.

The important function names to track are dfs, exist.

Guide

Why?

The code is doing bookkeeping so your brain does not have to keep the entire search space open at once.

  • The two-dimensional vector is the memory of the solution: grid state, DP state, or adjacency shape.
  • The final return is not magic; it is the invariant after the loops or recursion have finished doing their accounting.

Guide

How?

Walk through the solution in this order:

  1. Initialize the memory or helper structure.
  2. Process candidates in the order the invariant expects.
  3. Update the answer only when the current state is valid.
  4. Return the value that represents the fully processed input.

The most important competitive-programming habit here is to trust the invariant. Once the invariant is right, the loops become much less scary.

Guide

Complexity

  • Time: O(n) to O(n log n), depending on the dominant loop or data structure operation
  • Space: O(n) in the usual case for auxiliary containers or recursion

Guide

C++ Solution

Your submission

The accepted solution

solution.cpp
01//dfs
02//Runtime: 116 ms, faster than 54.80% of C++ online submissions for Word Search.
03//Memory Usage: 11.8 MB, less than 65.02% of C++ online submissions for Word Search.
04class Solution {
05public:
06    int m, n;
07    vector<vector<int>> dirs;
08    
09   	bool dfs(vector<vector<char>>& board, string& word, vector<vector<bool>>& visited, int ci, int cj, int cix) {
10        if(cix == word.size()){
11            return true;
12        }else if(board[ci][cj] != word[cix]){
13            return false;
14        }else{
15            // cout << cix << " : " << "(" << ci << ", " << cj << ")" << endl;
16            for(vector<int>& dir : dirs){
17                int ni = ci + dir[0];
18                int nj = cj + dir[1];
19                if(ni >= 0 && ni < m && nj >= 0 && nj < n && !visited[ni][nj]){
20                    visited[ni][nj] = true;
21                    if(dfs(board, word, visited, ni, nj, cix+1)) return true;
22                    visited[ni][nj] = false;
23                }
24            }
25            /*
26            to deal with the case: 
27            [["a"]]
28            "a"
29            */
30            return cix+1 == word.size();
31        }
32    };
33    
34    bool exist(vector<vector<char>>& board, string word) {
35        m = board.size();
36        if(m == 0) return false;
37        n = board[0].size();
38        if(n == 0) return false;
39        
40        dirs = {{0,1}, {0,-1}, {1,0}, {-1,0}};
41        
42        vector<vector<bool>> visited(m, vector<bool>(n, false));
43        
44        for(int i = 0; i < m; ++i){
45            for(int j = 0; j < n; ++j){
46                visited[i][j] = true;
47                if(dfs(board, word, visited, i, j, 0)){
48                    return true;
49                }
50                visited[i][j] = false;
51            }
52        }
53        
54        return false;
55    }
56};
57
58//dfs, remove visited array
59//https://leetcode.com/problems/word-search/discuss/27658/Accepted-very-short-Java-solution.-No-additional-space.
60//Runtime: 56 ms, faster than 81.21% of C++ online submissions for Word Search.
61//Memory Usage: 11.2 MB, less than 77.89% of C++ online submissions for Word Search.
62//time: O(M*N*4^L), in which L is the length of "word"
63//space: O(L), used by recursion
64class Solution {
65public:
66    int m, n;
67    vector<vector<int>> dirs;
68    
69    bool dfs(vector<vector<char>>& board, string& word, int ci, int cj, int cix){
70        if(cix == word.size()){
71            return true;
72        }else if(ci < 0 || ci >= m || cj < 0 || cj >= n){
73            return false;
74        }else if(board[ci][cj] != word[cix]){
75            return false;
76        }else{
77            // cout << "equal, " << cix << " : [" << ci << ", " << cj << "]: " << board[ci][cj] << endl;
78            //mark as visited
79            // cout << board[ci][cj] << " = " << (int)(board[ci][cj]) << ", 256-x: " << 256 - board[ci][cj] << ", x^256: " << (board[ci][cj]^256) << endl;
80            /*
81            // char c = 256^board[ci][cj];
82            // cout << "x == x^256? " << (board[ci][cj] == c) << endl;
83            the above statements evaluate to true,
84            so we cannot use:
85            // board[ci][cj] = 256^board[ci][cj];
86            in C++!!
87            */
88            //work
89            // board[ci][cj] = 256 - board[ci][cj];
90            //work
91            board[ci][cj] = '*';
92            for(vector<int>& dir : dirs){
93                int ni = ci + dir[0];
94                int nj = cj + dir[1];
95                if(dfs(board, word, ni, nj, cix+1)) return true;
96            }
97            //not work
98            // board[ci][cj] = 256^board[ci][cj];
99            //work
100            // board[ci][cj] = 256 - board[ci][cj];
101            //work
102            board[ci][cj] = word[cix];
103            return false;
104        }
105    };
106    
107    bool exist(vector<vector<char>>& board, string word) {
108        m = board.size();
109        if(m == 0) return false;
110        n = board[0].size();
111        if(n == 0) return false;
112        
113        dirs = {{0,1},{0,-1},{1,0},{-1,0}};
114        
115        for(int i = 0; i < m; ++i){
116            for(int j = 0; j < n; ++j){
117                if(dfs(board, word, i, j, 0)) return true;
118            }
119        }
120        
121        return false;
122    }
123};

Cost

Complexity

Time
O(n) to O(n log n), depending on the dominant loop or data structure operation
Dominated by the main traversal, recursion, or data-structure operations in the code.
Space
O(n) in the usual case for auxiliary containers or recursion
Auxiliary state plus the answer structure where the problem requires one.