Given a n,m which means the row and column of the 2D matrix and an array of pair A( size k). Originally, the 2D matrix is all 0 which means there is only sea in the matrix. The list pair has k operator and each operator has two integer A[i].x, A[i].y means that you can change the grid matrix[A[i].x][A[i].y] from sea to island. Return how many island are there in the matrix after each operator.
Example
Example 1:
Input: n = 4, m = 5, A = [[1,1],[0,1],[3,3],[3,4]]
Output: [1,1,2,2]
Explanation:
0. 00000
00000
00000
00000
1. 00000
01000
00000
00000
2. 01000
01000
00000
00000
3. 01000
01000
00000
00010
4. 01000
01000
00000
00011
分析:也是并查集的问题。如果邻居(上、下、左、有)是岛屿时,需要合并。
/** * 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 */ public ListnumIslands2(int n, int m, Point[] operators) { List res = new ArrayList<>(); if (operators == null || operators.length == 0) { return res; } int[] map = new int[n*m]; // 记录parent int cnt = 0; // 当前岛屿数 int[][] dirs = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}}; for (int i = 0; i < n*m; i++) { map[i] = -1; } for (Point p: operators) { int index = p.x * m + p.y; // 我先自成一派,再将左邻右派统统归于我门下 if (map[index] == -1) { // check if point 已经是岛屿 map[index] = index; cnt++; // 找四个方向 for (int i = 0; i < dirs.length; i++) { int x = p.x + dirs[i][0]; int y = p.y + dirs[i][1]; int nIndex = x * m + y; if (x < 0 || x >= n || y < 0 || y >= m || map[nIndex] == -1) { continue; } int nRoot = findRoot(nIndex, map); int root = findRoot(index, map); if (nRoot != root) { map[nRoot] = root; cnt--; } } } res.add(cnt); } return res; } private int findRoot(int i, int[] map) { if (i == map[i]) { return i; } return findRoot(map[i], map); } }