https://leetcode.com/problems/number-of-islands/description/
class UnionFound { public: vector<int> v; int cnt; UnionFound(int n) { v = vector<int>(n); for (int i = 0; i < n; i++) v[i] = i; cnt = n; } int findParent(int i) { if (v[i] == i) return i; v[i] = findParent(v[i]); return v[i]; } void Union(int p, int c) { int pp = findParent(p); int cp = findParent(c); if (pp != cp) { v[cp] = pp; cnt--; } } }; class Solution { public: int numIslands(vector<vector<char>>& grid) { int m = grid.size(); if (m == 0) return 0; int n = grid[0].size(); if (n == 0) return 0; UnionFound unionFound(m*n); int dirs[] = { -1, 0, 1, 0, -1 }; int zeros = 0; for (int i = 0; i < m; i++) for (int j = 0; j < n; j++) { if (grid[i][j] == '0') zeros++; else { for (int d = 0; d < 4; d++) { int x = i + dirs[d]; int y = j + dirs[d+1]; if (x >= 0 && x < m && y >= 0 && y < n && grid[x][y] == '1') { unionFound.Union(i*n+j, x*n+y); } } } } return unionFound.cnt - zeros; } };