305. Number of Islands II


題目:

A 2d grid map of m rows and n columns is initially filled with water. We may perform an addLand operation which turns the water at position (row, col) into a land. Given a list of positions to operate, count the number of islands after each addLand operation. An island is surrounded by water and is formed by connecting adjacent lands horizontally or vertically. You may assume all four edges of the grid are all surrounded by water.

Example:

Given m = 3, n = 3positions = [[0,0], [0,1], [1,2], [2,1]].
Initially, the 2d grid grid is filled with water. (Assume 0 represents water and 1 represents land).

0 0 0
0 0 0
0 0 0

Operation #1: addLand(0, 0) turns the water at grid[0][0] into a land.

1 0 0
0 0 0   Number of islands = 1
0 0 0

Operation #2: addLand(0, 1) turns the water at grid[0][1] into a land.

1 1 0
0 0 0   Number of islands = 1
0 0 0

Operation #3: addLand(1, 2) turns the water at grid[1][2] into a land.

1 1 0
0 0 1   Number of islands = 2
0 0 0

Operation #4: addLand(2, 1) turns the water at grid[2][1] into a land.

1 1 0
0 0 1   Number of islands = 3
0 1 0

We return the result as an array: [1, 1, 2, 3]

Challenge:

Can you do it in time complexity O(k log mn), where k is the length of the positions?

鏈接: http://leetcode.com/problems/number-of-islands-ii/

題解:

又是一道Union Find的經典題。這道題代碼主要參考了yavinci大神。風格還是princeton Sedgewick的那一套。這里我們可以把二維的Union-Find映射為一維的Union Find。使用Quick-Union就可以完成。但這樣的話Time Complexity是O(kmn)。 想要達到O(klogmn)的話可能還需要使用Weighted-Quick Union配合path compression。二刷一定要實現。

Time Complexity - O(mn * k), Space Complexity - O(mn)

public class Solution {
    int[][] directions = {{0, 1}, {1, 0}, {-1, 0}, {0, -1}};
    
    public List<Integer> numIslands2(int m, int n, int[][] positions) {
        List<Integer> res = new ArrayList<>();
        if(m < 0 || n < 0 || positions == null) {
            return res;
        }
        int[] id = new int[m * n];          // union find array
        int count = 0;
        Arrays.fill(id, -1);
        
        for(int i = 0; i < positions.length; i++) {
            int index = n * positions[i][0] + positions[i][1];
            if(id[index] != -1) {
                res.add(count);
                continue;
            }
            
            id[index] = index;
            count++;
            
            for(int[] direction : directions) {
                int x = positions[i][0] + direction[0];
                int y = positions[i][1] + direction[1];
                int neighborIndex = n * x + y;
                if(x < 0 || x >= m || y < 0 || y >= n || id[neighborIndex] == -1) {
                    continue;
                }
                if(!connected(id, index, neighborIndex)) {
                    union(id, neighborIndex, index);
                    count--;    
                }
            }
            
            res.add(count);
        }
        return res;
    }
    
    private boolean connected(int[] id, int p, int q) {
        return id[p] == id[q];
    }
    
    private void union(int[] id, int p, int q) {
        int pid = id[p];
        int qid = id[q];
        for(int i = 0; i < id.length; i++) {
            if(id[i] == pid) {
                id[i] = qid;
            }
        }
    }
}

 

二刷:

加入了Path compression以及Weight, 速度快了不少。

Time Complexity - (k * logmn)  Space Complexity - O(mn),  這里k是positions的長度

public class Solution {
    private int[] id;
    private int[] sz;
    private int[][] directions = {{0, 1}, {0, -1}, {1, 0}, {-1, 0}};
    public List<Integer> numIslands2(int m, int n, int[][] positions) {
        List<Integer> res = new ArrayList<>();
        if (positions == null || positions.length == 0 || m < 0 || n < 0) {
            return res;
        }
        id = new int[m * n]; 
        sz = new int[m * n];
        for (int i = 0; i < id.length; i++) {
            id[i] = i;
        }
        
        int count = 0;
        for (int[] position : positions) {
            int p = position[0] * n + position[1];
            sz[p]++;
            count++;
            for (int[] direction : directions) {
                int newRow = position[0] + direction[0];
                int newCol = position[1] + direction[1];
                if (newRow < 0 || newCol < 0 || newRow > m - 1 || newCol > n - 1) {
                    continue;
                }
                int q = newRow * n + newCol;
                if (sz[q] > 0) {
                    if (isConnected(p, q)) {
                        continue;    
                    } else {
                        union(p, q);
                        count--;
                    }
                }
            }
            res.add(count);
        }
        return res;
    }
    
    private int getRoot(int p) {
        while (p != id[p]) {
            id[p] = id[id[p]];
            p = id[p];
        } 
        return p;
    }
    
    private boolean isConnected(int p, int q) {
        return getRoot(p) == getRoot(q);
    }
    
    private void union(int p, int q) {
        int rootP = getRoot(p);
        int rootQ = getRoot(q);
        if (rootP == rootQ) {
            return;
        } else {
            if (sz[p] < sz[q]) {
                id[rootP] = rootQ;
                sz[q] += sz[p];
            } else {
                id[rootQ] = rootP;
                sz[p] += sz[q];
            }
        }
    }
}

 

 

 

Reference:

https://leetcode.com/discuss/69392/python-clear-solution-unionfind-class-weighting-compression

https://www.cs.princeton.edu/~rs/AlgsDS07/01UnionFind.pdf

https://leetcode.com/discuss/69397/my-simple-union-find-solution

https://leetcode.com/discuss/69572/easiest-15ms-java-solution-written-mins-with-explanations

https://leetcode.com/discuss/69585/union-find-java-implements

https://leetcode.com/discuss/69374/solution-using-union-find-path-compression-weight-balancing

https://leetcode.com/discuss/70392/java-union-find-solution

https://leetcode.com/discuss/72435/share-my-java-union-find-solution

https://leetcode.com/discuss/69513/simple-python-not-normal-union-find

http://algs4.cs.princeton.edu/15uf/


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM