博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Calculate Number Of Islands And Lakes 解答
阅读量:5311 次
发布时间:2019-06-14

本文共 3160 字,大约阅读时间需要 10 分钟。

Question

1 1 1 1 1 0

1 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遍历岛的时候,给相同的岛同样的标号。然后在遍历水的时候,检查包围的岛是否是相同标号。

1 import java.util.*; 2 import java.io.*; 3  4 public class Islands { 5     private static final int[][] directions = {
{0,1},{0,-1},{1,0},{-1,0}}; 6 7 public static void main(String[] args) { 8 int[][] island = { 9 {1, 1, 1, 1, 1, 0},10 {1, 0, 1, 0, 0, 1},11 {1, 0, 1, 0, 0, 1},12 {1, 1, 0, 1, 1, 1}13 };14 int m = island.length, n = island[0].length;15 // Calculate island number16 int color = 2;17 for (int i = 0; i < m; i++) {18 for (int j = 0; j < n; j++) {19 if (island[i][j] == 1) {20 dfs(island, color, i, j);21 color++;22 }23 }24 }25 int islandNum = color - 2;26 int lakeNum = 0;27 int surround = -2;28 for (int i = 0; i < m; i++) {29 for (int j = 0; j < n; j++) {30 if (island[i][j] == 0) {31 if (dfs2(island, surround, i, j)) {32 lakeNum++;33 }34 }35 }36 }37 System.out.println(islandNum);38 System.out.println(lakeNum);39 40 }41 42 private static void dfs(int[][] island, int color, int x, int y) {43 int m = island.length, n = island[0].length;44 island[x][y] = color;45 int newX, newY;46 for (int i = 0; i < 4; i++) {47 newX = x + directions[i][0];48 newY = y + directions[i][1];49 if (newX < 0 || newX >= m || newY < 0 || newY >= n)50 continue;51 if (island[newX][newY] != 1)52 continue;53 dfs(island, color, newX, newY);54 }55 }56 57 private static boolean dfs2(int[][] island, int surround, int x, int y) {58 int m = island.length, n = island[0].length;59 island[x][y] = -1;60 int newX, newY;61 for (int i = 0; i < 4; i++) {62 newX = x + directions[i][0];63 newY = y + directions[i][1];64 if (newX < 0 || newX >= m || newY < 0 || newY >= n)65 continue;66 int color = island[newX][newY];67 if (color == -1)68 continue;69 if (color != 0) {70 // This point is earth71 if (surround == -2) {72 surround = color;73 } else if (surround != color) {74 return false;75 }76 } else {77 if (!dfs2(island, surround, newX, newY))78 return false;79 }80 81 }82 return true;83 }84 }

 

转载于:https://www.cnblogs.com/ireneyanglan/p/4916420.html

你可能感兴趣的文章
在Xcode中编辑运行 Python 脚本
查看>>
bzoj1015:[JSOI2008]星球大战starwar
查看>>
Java HashMap和Hashtable的区别
查看>>
开机不登陆系统自动启动Vmware虚拟机(系统服务)
查看>>
线程相关函数(4)-pthread_mutex_lock(), pthread_mutex_unlock() 互斥锁
查看>>
学习新技术的 10 个建议
查看>>
浅谈Web网站架构演变过程
查看>>
css实现下拉菜单
查看>>
Spark Streaming事务处理彻底掌握
查看>>
数据的重要性
查看>>
解决合并检验反写收料通知单有小数的问题
查看>>
poj 2823单调队列模板题
查看>>
Linux内核配置浅析
查看>>
day 37 数据库MySQL的进一步认识
查看>>
python doc格式转文本格式
查看>>
SQL之经典SQL语句大全
查看>>
Autowired注解
查看>>
网络对抗技术 实验五
查看>>
Oracle init.ora常用配置详解
查看>>
SOME USEFUL MACHINE LEARNING LIBRARIES.
查看>>