Calculate Number Of Islands And Lakes 解答
2015-10-28 09:52
393 查看
Question
1 1 1 1 1 01 0 1 0 0 1
1 0 1 0 0 1
1 1 0 1 1 1
1 is earth, 0 is water.
i) count the number of 'islands' that the matrix has.
ii) count the number of 'lakes' that the matrix has i.e. connected clump of zeros that is entirely surrounded by a single island
Solution
这是Number of Islands的升级版。关键在于lake的定义,必须被同一个岛包围。所以我们在dfs遍历岛的时候,给相同的岛同样的标号。然后在遍历水的时候,检查包围的岛是否是相同标号。
import java.util.*; import java.io.*; public class Islands { private static final int[][] directions = {{0,1},{0,-1},{1,0},{-1,0}}; public static void main(String[] args) { int[][] island = { {1, 1, 1, 1, 1, 0}, {1, 0, 1, 0, 0, 1}, {1, 0, 1, 0, 0, 1}, {1, 1, 0, 1, 1, 1} }; int m = island.length, n = island[0].length; // Calculate island number int color = 2; for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { if (island[i][j] == 1) { dfs(island, color, i, j); color++; } } } int islandNum = color - 2; int lakeNum = 0; int surround = -2; for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { if (island[i][j] == 0) { if (dfs2(island, surround, i, j)) { lakeNum++; } } } } System.out.println(islandNum); System.out.println(lakeNum); } private static void dfs(int[][] island, int color, int x, int y) { int m = island.length, n = island[0].length; island[x][y] = color; int newX, newY; for (int i = 0; i < 4; i++) { newX = x + directions[i][0]; newY = y + directions[i][1]; if (newX < 0 || newX >= m || newY < 0 || newY >= n) continue; if (island[newX][newY] != 1) continue; dfs(island, color, newX, newY); } } private static boolean dfs2(int[][] island, int surround, int x, int y) { int m = island.length, n = island[0].length; island[x][y] = -1; int newX, newY; for (int i = 0; i < 4; i++) { newX = x + directions[i][0]; newY = y + directions[i][1]; if (newX < 0 || newX >= m || newY < 0 || newY >= n) continue; int color = island[newX][newY]; if (color == -1) continue; if (color != 0) { // This point is earth if (surround == -2) { surround = color; } else if (surround != color) { return false; } } else { if (!dfs2(island, surround, newX, newY)) return false; } } return true; } }
相关文章推荐
- 配置Tomcat使用https协议(配置SSL协议)
- js中3元运算符写法
- 【JavaWeb】Access restriction The type is not accessible due to restriction on required library
- 【Java TCP/IP Socket】构建和解析自定义协议消息(含代码)
- awk 运算符
- 微信公众号设置菜单 发布资讯
- 每天一个linux命令(24):Linux文件类型与扩展名
- 省市级二级联动下拉列表框
- 学习windows驱动(回顾1)
- switch ....case
- windows下安装nodejs和express
- 西秦的ACE-Python教程 一、Python本地开发环境部署
- 获取*.jks签名的方法(Android studio)
- webview不能正常调用Javascript代码
- 经常使用的web安全测试工具
- mongo 过滤 分组查询
- 感谢dudu和他的博客园团队
- ios 微博第三方登录及得到相关参数
- 如何获取不同cell上的button点击事件
- Windows下使用MinGW+msys编译FFmpeg错误