200. Number of Islands
https://leetcode.com/problems/number-of-islands/description/
Thoughts
Code
/*
* @lc app=leetcode id=200 lang=cpp
*
* [200] Number of Islands
*/
// @lc code=start
class Solution {
class UF {
public:
vector<int> parent;
int size = 0;
UF(const int N): parent(N) {
for (int i = 0; i < N; ++i) {
parent[i] = i;
}
}
void un(int x, int y) {
x = find(x);
y = find(y);
if (x != y) {
parent[x] = y;
--size;
}
}
int find(int x) {
while (x != parent[x]) {
x = parent[x];
parent[x] = parent[parent[x]];
}
return x;
}
};
public:
int numIslands(vector<vector<char>>& grid) {
const int M = grid.size(), N = M == 0 ? 0 : grid[0].size();
UF uf(M * N);
vector<vector<int>> dirs{{-1, 0}, {1, 0}, {0, -1}, {0, 1}};
for (int i = 0; i < M; ++i) {
for (int j = 0; j < N; ++j) {
if (grid[i][j] == '0') continue;
++uf.size;
for (const auto &d : dirs) {
int x = i + d[0], y = j + d[1];
if (x >= 0 && x < M && y >= 0 && y < N && grid[x][y] == '1') {
uf.un(i * N + j, x * N + y);
}
}
}
}
return uf.size;
}
};
// @lc code=end
Analysis
Last updated