[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<int> father;
    vector<vector<int> > 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<int> numIslands2(int n, int m, vector<Point>& 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<int> 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;
    }
};
    原文作者:楷书
    原文地址: https://www.jianshu.com/p/246d231bffa6
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞