/** 305.Number of Islands II * 2016-4-3 by Mingyang *union Find topic, skip directly*/ Private int[] dir = {{0, 1}, {0,-1}, {-1, 0}, {1, 0}}; PublicList<integer> NumIslands2 (intMintNint[] positions) {unionfind2d Islands=Newunionfind2d (M, n); List<Integer> ans =NewArraylist<integer>(); for(int[] position:positions) { intx = position[0], y = position[1]; intp =islands.add (x, y); for(int[] d:dir) { intQ = islands.getid (x + d[0], y + d[1]); if(q > 0 &&!)Islands.find (P, Q)) Islands.unite (P, q); } ans.add (Islands.size ()); } returnans; }}classunionfind2d {Private int[] ID; Private int[] sz; Private intm, N, Count; PublicUNIONFIND2D (intMintN) { This. Count = 0; This. N =N; This. m =m; This. ID =New int[M * n + 1]; This. Sz =New int[M * n + 1]; } Public intIndexintXintY) {returnX * n + y + 1; } Public intSize () {return This. Count;} Public intGetID (intXinty) {if(0 <= x && x < m && 0<= y && y <N)returnid[index (x, y)]; return0; } Public intAddintXinty) {inti =index (x, y); Id[i]= i; Sz[i] = 1; ++count; returni; } Public BooleanFindintPintq) {returnRoot (p) = =root (q); } Public voidUniteintPintq) {inti = root (p), j =root (q); if(Sz[i] < sz[j]) {//Weighted Quick UnionId[i] = j; SZ[J] + =Sz[i]; } Else{Id[j]= i; Sz[i] + =Sz[j]; } --count; } Private intRootinti) { for(; I! = Id[i]; i =Id[i]) id[i]= Id[id[i]];//Path Compression returni; }}
305.Number of Islands II