标签:
/* * 200.Number of Islands * 2016-4-3 by Mingyang * union 什么:两个相邻的1元素 * union 目的:union后计数union集合数量(通过计数union数组中根节点数量) */ class UF { public int count = 0; public int[] id = null; public UF(int m, int n, char[][] grid) { for(int i = 0; i < m; i++) { for(int j = 0; j < n; j++) { if(grid[i][j] == ‘1‘) count++; } } id = new int[m * n]; for(int i = 0; i < m * n; i++) { id[i] = i; } } public int find(int p) { while(p != id[p]) { id[p] = id[id[p]]; p = id[p]; } return p; } public boolean isConnected(int p, int q) { int pRoot = find(p); int qRoot = find(q); if(pRoot != qRoot) return false; else return true; } public void union(int p, int q) { int pRoot = find(p); int qRoot = find(q); if(pRoot == qRoot) return; id[pRoot] = qRoot; count--; } } public int numIslands(char[][] grid) { if(grid.length == 0 || grid[0].length == 0) return 0; int m = grid.length, n = grid[0].length; UF uf = new UF(m , n, grid); for(int i = 0; i < m; i++) { for(int j = 0; j < n; j++) { if(grid[i][j] == ‘0‘) continue; int p = i * n + j; int q; 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); } } } return uf.count; } //当然你也会觉得下面的可能更简单,那就是另外一种情况了,我就是用下面的方法做的 //设一个叫count的值,没遇到一个1,就把所有相连的1全部变为0,这样,到底遇到几次1,就是最终有几个小岛啦 public int numIslands2(char[][] grid) { if (grid == null || grid.length == 0 || grid[0].length == 0) return 0; int count = 0; for (int i = 0; i < grid.length; i++) { for (int j = 0; j < grid[0].length; j++) { if (grid[i][j] == ‘1‘) { count++; dfs(grid, i, j); } } } return count; } public void dfs(char[][] grid, int i, int j) { // 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 land dfs(grid, i - 1, j); dfs(grid, i + 1, j); dfs(grid, i, j - 1); dfs(grid, i, j + 1); }
标签:
原文地址:http://www.cnblogs.com/zmyvszk/p/5569437.html