[LeetCode]Number of Islands II

MS面试最后一轮就跪在number of island 1 了,痛心啊。bfs虽然能过lc,但是面试的时候得写出union find来才可以啊。

public class Solution {
    private int[] array;
    private int[][] grid;
    private int m, n;
    private int count = 0;
    public List<Integer> numIslands2(int m, int n, int[][] positions) {
        array = new int[m * n];
        grid = new int[m][n];
        Arrays.fill(array, -1);
        this.m = m;
        this.n = n;
        List<Integer> result = new ArrayList<Integer>();
        int length = positions.length;
        for (int i = 0; i < length; i++) {
            int r = positions[i][0];
            int c = positions[i][1];
            int x = r * n + c;
            array[x] = x;
            grid[r][c] = 1;
            count ++;
            if (r > 0 && grid[r - 1][c] == 1) {
                set(r - 1, c, r , c);
            }
            if (r + 1 < m && grid[r + 1][c] == 1) {
                set(r + 1, c, r , c);
            }
            if (c > 0 && grid[r][c - 1] == 1) {
                set(r, c - 1, r , c);
            }
            if (c + 1 < n && grid[r][c + 1] == 1) {
                set(r, c + 1, r ,c);
            }
            result.add(count);
        }
        return result;
    }
    public int find(int x) {
        int y = array[x];
        if (y != -1 && y != x) {
            return find(y);
        }
        return y;
    }
    public void set(int r1, int c1, int r2, int c2) {
        int x1 = r1 * n + c1;
        int x2 = r2 * n + c2;
        int tmp1 = find(x1);
        int tmp2 = find(x2);
        if (tmp1 == -1) {
            array[x1] = tmp2;
        }
        if (tmp1 != tmp2) {
            count--;
        }
        array[tmp1] = tmp2;
    }
}

 

posted @ 2015-12-15 07:04  Weizheng_Love_Coding  阅读(221)  评论(0编辑  收藏  举报