← Home

200. Number of Islands

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

I like to read this solution as a small machine: keep the useful information, throw away the noise. For 200. Number of Islands, the solution in this repository is mainly a union-find solution.

Guide

What?

The code is easier to read if we treat it as a controlled search through possible states. 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.

Guide

When?

Use this approach when the hard part is not syntax, but deciding what must stay true after every update. The accepted code reduces that pressure by storing exactly the information that remains useful later.

The important function names to track are numIslands, unite.

Guide

Why?

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

  • A set is doing the membership or uniqueness work, which keeps the main loop readable.
  • 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. 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//Runtime: 44 ms, faster than 7.77% of C++ online submissions for Number of Islands.
02//Memory Usage: 12.2 MB, less than 12.36% of C++ online submissions for Number of Islands.
03class Solution {
04public:
05    int numIslands(vector<vector<char>>& grid) {
06        int m = grid.size();
07        if(m == 0) return 0;
08        int n = grid[0].size();
09        
10        queue<vector<int>> q;
11        int i = 0;
12        vector<vector<int>> dirs = {
13            {1,0},
14            {-1,0},
15            {0,1},
16            {0,-1}
17        };
18        vector<vector<bool>> visited(m, vector(n, false));
19        int ans = 0;
20        
21        while(i < m*n){
22            while(i < m*n && !(!visited[i/n][i%n] && grid[i/n][i%n] == '1')){
23                i++;
24            }
25            if(i >= m*n) break;
26            // cout << i/n << " " << i%n << endl;
27            
28            visited[i/n][i%n] = true;
29            q.push({i/n, i%n});
30            ans++;
31
32            //visite all cell connected to it
33            while(!q.empty()){
34                vector<int> cur = q.front(); q.pop();
35                int curI = cur[0], curJ = cur[1];
36
37                // cout << "cur: " << curI << " " << curJ << endl;
38
39                for(vector<int>& dir : dirs){
40                    int newI = curI + dir[0];
41                    int newJ = curJ + dir[1];
42                    if(newI >= 0 && newI < m && newJ >= 0 && newJ < n && !visited[newI][newJ] && grid[newI][newJ] == '1'){
43                        visited[newI][newJ] = true;
44                        q.push({newI, newJ});
45                    }
46                }
47            }
48        }
49        
50        // cout << endl << endl;
51        
52        return ans;
53    }
54};
55
56//Union Find
57//Runtime: 24 ms, faster than 16.98% of C++ online submissions for Number of Islands.
58//Memory Usage: 9.1 MB, less than 100.00% of C++ online submissions for Number of Islands.
59class DSU{
60public:
61    vector<int> parent;
62    
63    DSU(int n){
64        parent= vector<int>(n);
65        iota(parent.begin(), parent.end(), 0);
66    };
67    
68    int find(int x){
69        if(parent[x] != x){
70            parent[x] = find(parent[x]);
71        }
72        return parent[x];
73    };
74    
75    void unite(int x, int y){
76        // parent[x] = find(parent[y]);
77        // parent[y] = find(parent[x]);
78        parent[find(x)] = find(y);
79    };
80};
81
82class Solution {
83public:
84    int numIslands(vector<vector<char>>& grid) {
85        int m = grid.size();
86        if(m == 0) return 0;
87        int n = grid[0].size();
88        
89        vector<vector<int>> dirs = {
90            {1,0},
91            {-1,0},
92            {0,1},
93            {0,-1}
94        };
95        
96        DSU dsu(m*n);
97        
98        for(int i = 0; i < m; i++){
99            for(int j = 0; j < n; j++){
100                // cout << "cur: " << i << " " << j << endl;
101                if(grid[i][j] != '1') continue;
102                for(vector<int>& dir : dirs){
103                    int newI = i + dir[0];
104                    int newJ = j + dir[1];
105                    if(newI >= 0 && newI < m && newJ >= 0 && newJ < n && grid[newI][newJ] == '1'){
106                        // cout << newI << " " << newJ << endl;
107                        dsu.unite(i*n+j, newI*n+newJ);
108                        // cout << "(" << i << ", " << j << ", " << dsu.parent[i*n+j] << "), (" << newI << ", " << newJ << ", " << dsu.parent[newI*n+newJ] << ")" << endl;
109                    }
110                    
111                }
112            }
113        }
114        
115        set<int> uniqParent;
116        
117        for(int i = 0; i < m; i++){
118            for(int j = 0; j < n; j++){
119                if(grid[i][j] == '1'){
120                    // cout << i << " " << j << " " << dsu.find(i*n+j) << endl;
121                    uniqParent.insert(dsu.find(i*n+j));
122                }
123            }
124        }
125        
126        return uniqParent.size();
127    }
128};

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.