/** 200.Number of Islands * 2016-4-3 by Mingyang * Union what: two adjacent 1 elements * Union purpose: Union count Union Number of collections (by counting the number of root nodes in the Union array)*/ classUF { Public intCount = 0; Public int[] id =NULL; PublicUF (intMintNChar[] grid) { for(inti = 0; I < m; i++) { for(intj = 0; J < N; J + +) { if(Grid[i][j] = = ' 1 ') count++; }} ID=New int[M *N]; for(inti = 0; I < M * N; i++) {Id[i]=i; } } Public intFindintp) { while(P! =Id[p]) {Id[p]=Id[id[p]]; P=Id[p]; } returnp; } Public BooleanIsConnected (intPintq) {intProot =find (P); intQroot =find (q); if(Proot! = qroot)return false; Else return true; } Public voidUnionintPintq) {intProot =find (P); intQroot =find (q); if(Proot = = qroot)return; Id[proot]=Qroot; Count--; } } Public intNumislands (Char[] grid) { if(Grid.length = = 0 | | grid[0].length = = 0)return0; intm = grid.length, n = grid[0].length; UF UF=NewUF (M, N, Grid); for(inti = 0; I < m; i++) { for(intj = 0; J < N; J + +) { if(Grid[i][j] = = ' 0 ')Continue; intp = i * n +J; intQ; if(i > 0 && grid[i-1][j] = = ' 1 ') {Q= P-N; Uf.union (P, q); } if(I < m-1 && grid[i + 1][j] = = ' 1 ') {Q= p +N; Uf.union (P, q); } if(J > 0 && grid[i][j-1] = = ' 1 ') {Q= P-1; Uf.union (P, q); } if(J < n-1 && grid[i][j + 1] = = ' 1 ') {Q= p + 1; Uf.union (P, q); } } } returnUf.count; } //Of course, you will feel that the following may be more simple, that is another situation, I just do it in the following way//set a value called count, did not encounter a 1, will all the connected 1 all become 0, so that, in the end, encountered several times 1, is eventually a few small islands Public intNUMISLANDS2 (Char[] grid) { if(Grid = =NULL|| Grid.length = = 0 | | Grid[0].length = = 0) return0; intCount = 0; for(inti = 0; i < grid.length; i++) { for(intj = 0; J < Grid[0].length; J + +) { if(Grid[i][j] = = ' 1 ') {Count++; DFS (grid, I, j); } } } returncount; } Public voidDfsChar[] Grid,intIintj) {//Validity checking if(I < 0 | | J < 0 | | i > GRID.LENGTH-1 | | J > grid[0].length-1) return; //if current cell is water or visited if(grid[i][j]! = ' 1 ') return; //set visited cell to ' 0 'GRID[I][J] = ' 0 '; //Merge all adjacent landDFS (grid, i-1, J); DFS (grid, I+ 1, J); DFS (grid, I, J-1); DFS (grid, I, J+ 1); }
200.Number of Islands