[LeetCode] Number of Islands II

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

Analysis: and also look into the problem sets. If the neighbors (top, bottom, left, and there are) islands, need to be merged.

/**
 * 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 List<Integer> numIslands2(int n, int m, Point[] operators) {
        List<Integer> 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* = m + PX index Py;
             // I first faction, then left o I attributed all right door 
            IF (Map [index] == -1) {    // Check Point already IF island 
                map [index] = index; 
                CNT ++ ; 
            
            
                // find four directions 
                for ( int I = 0; I <dirs.length; I ++ ) {
                     int X = PX + dirs [I] [0]; int Y = Py + dirs [I] [. 1 ];
                     int nIndex = m + X * Y;
                     IF (X <0 || X> = Y n-|| <|| 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);
    }

}

 

Guess you like

Origin www.cnblogs.com/yinger33/p/10961865.html