Number of Islands II
Example
Note
Code
/**
* Definition for a point.
* class Point {
* int x;
* int y;
* Point() { x = 0; y = 0; }
* Point(int a, int b) { x = a; y = b; }
* }
*/
public class Solution {
/**
* @param n: An integer
* @param m: An integer
* @param operators: an array of point
* @return: an integer array
*/
private static class UnionFind {
int[] father;
public UnionFind(int n) {
father = new int[n];
for (int i = 0; i < n; i++) {
father[i] = i;
}
}
private int find(int x) {
if (father[x] == x) {
return x;
}
return father[x] = find(father[x]);
}
private void union(int a, int b) {
int root_a = find(a);
int root_b = find(b);
father[root_a] = root_b;
}
}
public List<Integer> numIslands2(int m, int n, Point[] operators) {
// write your code here
UnionFind uf = new UnionFind(m * n);
int[][] grids = new int[m][n];
int[] dx = {0, -1, 0, 1};
int[] dy = {1, 0, -1, 0};
List<Integer> ans = new ArrayList<>();
int count = 0;
if (operators == null || operators.length == 0) {
return ans;
}
for (Point op : operators) {
int x = op.x;
int y = op.y;
if (grids[x][y] != 1) {
count++;
grids[x][y] = 1;
int id = converttoId(x, y, n);
for (int i = 0; i < 4; i++) {
int nx = x + dx[i];
int ny = y + dy[i];
if (0 <= nx && nx < m &&
0 <= ny && ny < n && grids[nx][ny] == 1) {
int nid = converttoId(nx, ny, n);
int fa = uf.find(id);
int nfa = uf.find(nid);
if (fa != nfa) {
count--;
uf.union(id, nid);
}
}
}
}
ans.add(count);
}
return ans;
}
private int converttoId(int x, int y, int m){
return x * m + y;
}
}Last updated