[LintCode][Union Find] Number of Islands II

Problem

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.

Notice

0 is represented as the sea, 1 is represented as the island. If two 1 is adjacent, we consider them in the same island. We only consider up/down/left/right adjacent.

Example

Given n = 3, m = 3, array of pair A = [(0,0),(0,1),(2,2),(2,1)].

return [1,1,2,2].

Solution

并查集。每次添加一片海,都查看左右上下海所属哪片海,然后更新他们。

/**
 * Definition for a point.
 * struct Point {
 *     int x;
 *     int y;
 *     Point() : x(0), y(0) {}
 *     Point(int a, int b) : x(a), y(b) {}
 * };
 */
class Solution {
private:
    vector father;
    vector > matrix;
    int step[4][2] = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};
public:
    /**
     * @param n an integer
     * @param m an integer
     * @param operators an array of point
     * @return an integer array
     */
    vector numIslands2(int n, int m, vector& operators) {
        father.resize(n * m);
        matrix.resize(n);
        for(int i = 0; i < n; i++) {
            matrix[i].resize(m);
            for(int j = 0; j < m; j++) {
                father[i * m  + j] = i * m + j;
                matrix[i][j] = 0;
            }
        }
        
        int count = 0;
        vector ret;
        for(int i = 0; i < operators.size(); i++) {
            int x = operators[i].x;
            int y = operators[i].y;
            int newFather = x * m + y;
            count++;
            matrix[x][y] = 1;
            for(int j = 0; j < 4; j++) {
                int newX = x + step[j][0];
                int newY = y + step[j][1];
                int index = newX * m + newY;
                if (0 <= newX && newX < n && 0 <= newY && newY < m && matrix[newX][newY] == 1) {
                    int f = findFather(index);
                    if (f != newFather) {
                        father[f] = newFather;
                        count--;
                    }
                }
            }
            ret.push_back(count);
        }
        
        return ret;
    }
    
    int findFather(int index) {
        int startIndex = index;
        while(father[index] != index) {
            index = father[index];
        }
        
        // road compress
        while (father[startIndex] != startIndex) {
            int nextIndex = father[startIndex];
            father[startIndex] = index;
            startIndex = nextIndex;
        }
        
        return index;
    }
};

你可能感兴趣的:([LintCode][Union Find] Number of Islands II)