← Home

130. Surrounded Regions

LeetCode article · C++ solution
Website made by wuisabel-gif · Original C++ code by keineahnung2345
union-findC++Markdown
130

This problem looks busy at first, but the accepted solution is built around one steady invariant. For 130. Surrounded Regions, the solution in this repository is mainly a union-find solution.

Guide

What?

We want to turn the problem statement into a smaller set of decisions the computer can repeat safely. 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: union-find, graph traversal.

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

  • bfs

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 solve, changeNeighbor, unite, isConnected, node.

Guide

Why?

The win comes from making each line carry responsibility: store the useful state, discard the rest, keep moving.

  • The queue gives the solution a level-by-level or frontier-style traversal.
  • 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. Start from the smallest reliable state.
  2. Expand one legal move at a time.
  3. Cache, count, or merge information as soon as it becomes settled.
  4. Let the final stored value answer the original question.

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//bfs
02//Runtime: 80 ms, faster than 5.44% of C++ online submissions for Surrounded Regions.
03//Memory Usage: 19.1 MB, less than 8.24% of C++ online submissions for Surrounded Regions.
04class Solution {
05public:
06    void solve(vector<vector<char>>& board) {
07        int m = board.size();
08        if(m == 0) return;
09        int n = board[0].size();
10        if(n == 0) return;
11        vector<vector<bool>> visited(m, vector<bool>(n, false));
12        vector<vector<int>> dirs = {
13            {0,1},
14            {0,-1},
15            {1,0},
16            {-1,0}
17        };
18        vector<vector<int>> component;
19        vector<int> cur;
20        
21        for(int i = 0; i < m; ++i){
22            for(int j = 0; j < n; ++j){
23                bool surrounded = true;
24                component.clear();
25                if(board[i][j] == 'O' && !visited[i][j]){
26                    queue<vector<int>> q;
27                    q.push({i, j});
28                    visited[i][j] = true;
29                    
30                    while(!q.empty()){
31                        cur = q.front(); q.pop();
32                        if(cur[0] == 0 || cur[0] == m-1 || cur[1] == 0 || cur[1] == n-1){
33                            surrounded = false;
34                        }
35                        component.push_back(cur);
36                        
37                        for(vector<int>& dir : dirs){
38                            int ni = cur[0] + dir[0];
39                            int nj = cur[1] + dir[1];
40                            if(ni >= 0 && ni < m && nj >= 0 && nj < n && board[ni][nj] == 'O' && !visited[ni][nj]){        
41                                visited[ni][nj] = true;
42                                q.push({ni, nj});
43                            }
44                        }
45                    }
46                }
47                
48                if(surrounded && !component.empty()){
49                    for(vector<int>& cur : component){
50                        board[cur[0]][cur[1]] = 'X';
51                    }
52                }
53            }
54        }
55    }
56};
57
58//bfs
59//https://leetcode.com/problems/surrounded-regions/discuss/41612/A-really-simple-and-readable-C%2B%2B-solutionuff0conly-cost-12ms
60//Runtime: 32 ms, faster than 54.14% of C++ online submissions for Surrounded Regions.
61//Memory Usage: 11 MB, less than 44.85% of C++ online submissions for Surrounded Regions.
62class Solution {
63public:
64    int m, n;
65    vector<vector<bool>> visited;
66    vector<vector<int>> dirs;
67    vector<int> cur;
68    
69    void changeNeighbor(vector<vector<char>>& board, int i, int j, char src, char dst){
70        queue<vector<int>> q;
71        q.push({i, j});
72        visited[i][j] = true;
73
74        while(!q.empty()){
75            cur = q.front(); q.pop();
76            board[cur[0]][cur[1]] = dst;
77
78            for(vector<int>& dir : dirs){
79                int ni = cur[0] + dir[0];
80                int nj = cur[1] + dir[1];
81                if(ni >= 0 && ni < m && nj >= 0 && nj < n && board[ni][nj] == 'O' && !visited[ni][nj]){
82                    visited[ni][nj] = true;
83                    q.push({ni, nj});
84                }
85            }
86        }
87    };
88    
89    void solve(vector<vector<char>>& board) {
90        m = board.size();
91        if(m == 0) return;
92        n = board[0].size();
93        if(n == 0) return;
94        visited = vector<vector<bool>>(m, vector<bool>(n, false));
95        dirs = {
96            {0,1},
97            {0,-1},
98            {1,0},
99            {-1,0}
100        };
101        
102        for(int j = 0; j < n; ++j){
103            for(int i : {0, m-1}){
104                if(board[i][j] == 'O' && !visited[i][j]){
105                    changeNeighbor(board, i, j, 'O', '1');
106                }
107            }
108        }
109        
110        for(int i = 0; i < m; ++i){
111            for(int j : {0, n-1}){
112                if(board[i][j] == 'O' && !visited[i][j]){
113                    changeNeighbor(board, i, j, 'O', '1');
114                }
115            }
116        }
117        
118        for(int i = 0; i < m; ++i){
119            for(int j = 0; j < n; ++j){
120                if(board[i][j] == 'O'){
121                    board[i][j] = 'X';
122                }else if(board[i][j] == '1'){
123                    board[i][j] = 'O';
124                }
125            }
126        }
127    }
128};
129
130//union find
131//https://leetcode.com/problems/surrounded-regions/discuss/41617/Solve-it-using-Union-Find
132//Runtime: 36 ms, faster than 41.79% of C++ online submissions for Surrounded Regions.
133//Memory Usage: 10.4 MB, less than 63.29% of C++ online submissions for Surrounded Regions.
134class DSU{
135public:
136    vector<int> parent;
137    
138    DSU(int N){
139        parent = vector<int>(N);
140        iota(parent.begin(), parent.end(), 0);
141    };
142    
143    //wrong implementation
144    // int find(int x){
145    //     if(parent[x] == x){
146    //         return x;
147    //     }
148    //     return parent[x] = find(parent[x]);
149    // };
150    
151    int find(int x){
152        if(parent[x] != x){ //initial state
153            parent[x] = find(parent[x]);
154        }
155        return parent[x];
156    }
157    
158    void unite(int x, int y){
159        parent[find(x)] = find(y);
160    };
161    
162    bool isConnected(int x, int y){
163        return find(x) == find(y);
164    }
165};
166
167class Solution {
168public:
169    int m, n;
170    
171    int node(int i, int j){
172        return i*n+j;
173    };
174    
175    void solve(vector<vector<char>>& board) {
176        m = board.size();
177        if(m == 0) return;
178        n = board[0].size();
179        if(n == 0) return;
180        
181        vector<vector<int>> dirs = {
182            {0,1},
183            {0,-1},
184            {1,0},
185            {-1,0}
186        };
187        
188        //[0, m*n-1] for each cell, m*n for dummy cell
189        DSU dsu(m*n+1);
190        int dummyNode = m*n;
191        
192        for(int i = 0; i < m; ++i){
193            for(int j = 0; j < n; ++j){
194                if(board[i][j] != 'O') continue;
195                if(i == 0 || i == m-1 || j == 0 || j == n-1){
196                    dsu.unite(node(i, j), dummyNode);
197                }else{
198                    for(vector<int>& dir : dirs){
199                        int ni = i + dir[0];
200                        int nj = j + dir[1];
201                        if(ni >= 0 && ni < m && nj >= 0 && nj < n && board[ni][nj] == 'O'){
202                            dsu.unite(node(ni, nj), node(i, j));
203                        }
204                    }
205                    //another implementation
206                    // if(i > 0 && board[i-1][j] == 'O')  dsu.unite(node(i,j), node(i-1,j));
207                    // if(i < m-1 && board[i+1][j] == 'O')  dsu.unite(node(i,j), node(i+1,j));
208                    // if(j > 0 && board[i][j-1] == 'O')  dsu.unite(node(i,j), node(i, j-1));
209                    // if(j < n-1 && board[i][j+1] == 'O')  dsu.unite(node(i,j), node(i, j+1));
210                }
211            }
212        }
213        
214        for(int i = 0; i < m; ++i){
215            for(int j = 0; j < n; ++j){
216                if(dsu.isConnected(node(i, j), dummyNode)){
217                    board[i][j] = 'O';
218                }else{
219                    board[i][j] = 'X';
220                }
221            }
222        }
223    }
224};

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.