1 public class Solution { 2 private int count; 3 private int[] parent; 4 public List<Integer> numIslands2(int m, int n, int[][] positions) { 5 List<Integer> result = new ArrayList<>(); 6 if (positions.length == 0) { 7 return result; 8 } 9 parent = new int[m*n]; 10 int[][] islands = new int[m][n]; 11 count = 0; 12 13 for (int i = 0; i < parent.length; i++) { 14 parent[i] = i; 15 } 16 17 for (int[] position : positions) { 18 int x = position[0]; 19 int y = position[1]; 20 islands[x][y] = 1; 21 count++; 22 23 if (x > 0 && islands[x - 1][y] == 1) { 24 union(x*n + y, (x - 1)*n + y); 25 } 26 27 if (x < m - 1 && islands[x + 1][y] == 1) { 28 union(x*n + y, (x + 1)*n + y); 29 } 30 31 if (y > 0 && islands[x][y - 1] == 1) { 32 union(x*n + y, x * n + y - 1); 33 } 34 35 if (y < n - 1 && islands[x][y + 1] == 1) { 36 union(x*n + y, x * n + y + 1); 37 } 38 result.add(count); 39 } 40 return result; 41 } 42 43 private void union(int a, int b) { 44 int indexA = findParent(a); 45 int indexB = findParent(b); 46 if (indexA != indexB) { 47 count--; 48 parent[indexA] = parent[indexB]; 49 } 50 } 51 52 private int findParent(int x) { 53 while (x != parent[x]) { 54 parent[x] = parent[parent[x]]; 55 x = parent[x]; 56 } 57 return x; 58 } 59 }