Problem solution · C++

Number of Islands II

Number of Islands II: a C++ solution using disjoint set union. Learn the idea, check the complexity, and read the full code, with credit to walkccc LeetCode Solutions.

Technique
Disjoint set union
Source
walkccc LeetCode Solutions
Length
76 lines
Start with the idea.

Try the problem first. If you get stuck, read the approach below, then write your own solution. The full code is at the bottom.

Approach

Disjoint set union

For Number of Islands II, the implementation maintains connected components and merges them as relationships are processed.

  1. Give each element a component representative.
  2. Merge representatives when a connection is accepted.
  3. Answer connectivity or component queries from the compressed representatives.

Code notes

  • 76 lines of C++ from the credited upstream file 305.cpp.
  • The implementation visibly relies on sequence storage.
  • 2 loop blocks detected.

Complexity

Account for every find and union operation; with path compression and ranked merging, the amortized cost is nearly constant per operation.

Check the problem constraints before deciding whether this complexity will pass.

Source

Code and credit

This code comes from walkccc LeetCode Solutions by P.-Y. Chen (walkccc) and is used under the MIT licence.

Full codeNumber of Islands II · C++C++
Use this to learn the idea, then write your own version.
class UnionFind { public:  vector<int> id;   UnionFind(int n) : id(n, -1), rank(n) {}   void unionByRank(int u, int v) {    const int i = find(u);    const int j = find(v);    if (i == j)      return;    if (rank[i] < rank[j]) {      id[i] = j;    } else if (rank[i] > rank[j]) {      id[j] = i;    } else {      id[i] = j;      ++rank[j];    }  }   int find(int u) {    return id[u] == u ? u : id[u] = find(id[u]);  }  private:  vector<int> rank;}; class Solution { public:  vector<int> numIslands2(int m, int n, vector<vector<int>>& positions) {    constexpr int kDirs[4][2] = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};    vector<int> ans;    vector<vector<bool>> seen(m, vector<bool>(n));    UnionFind uf(m * n);    int count = 0;     for (const vector<int>& p : positions) {      const int i = p[0];      const int j = p[1];      if (seen[i][j]) {        ans.push_back(count);        continue;      }      seen[i][j] = true;      const int id = getId(i, j, n);      uf.id[id] = id;      ++count;      for (const auto& [dx, dy] : kDirs) {        const int x = i + dx;        const int y = j + dy;        if (x < 0 || x == m || y < 0 || y == n)          continue;        const int neighborId = getId(x, y, n);        if (uf.id[neighborId] == -1)  // water          continue;        const int currentRoot = uf.find(id);        const int neighborRoot = uf.find(neighborId);        if (currentRoot != neighborRoot) {          uf.unionByRank(currentRoot, neighborRoot);          --count;        }      }      ans.push_back(count);    }     return ans;  }  private:  int getId(int i, int j, int n) {    return i * n + j;  }}; 

Did this explanation save you time? I'm a Grade 11 student building this free library to make difficult algorithms easier to understand.

Buy me a coffee ↗