博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
[LintCode] Number of Islands(岛屿个数)
阅读量:6989 次
发布时间:2019-06-27

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

hot3.png

描述

给一个01矩阵,求不同的岛屿的个数。

0代表海,1代表岛,如果两个1相邻,那么这两个1属于同一个岛。我们只考虑上下左右为相邻。

样例

在矩阵:

[  [1, 1, 0, 0, 0],  [0, 1, 0, 0, 1],  [0, 0, 0, 1, 1],  [0, 0, 0, 0, 0],  [0, 0, 0, 0, 1]]

中有 3 个岛。

 

代码

GitHub 的源代码,请访问下面的链接:

package com.ossez.lang.tutorial.tests.lintcode;import org.junit.Test;import org.slf4j.Logger;import org.slf4j.LoggerFactory;/** * 

* 433 *

*

* * @author YuCheng * */public class LintCode0433NumIslandsTest { private final static Logger logger = LoggerFactory.getLogger(LintCode0433NumIslandsTest.class); /** * */ @Test public void testMain() { logger.debug("BEGIN"); // INIT GRID boolean[][] grid = { { true, true, false, false, false }, { false, true, false, false, true }, { false, false, false, true, true }, { false, false, false, false, false }, { false, false, false, false, true } }; // NULL CHECK if (grid.length == 0 || grid[0].length == 0) { System.out.println("NULL"); // return 0; } // GET SIZE int n = grid.length; int m = grid[0].length; // ARRAY FOR VISITED LOG boolean[][] visited = new boolean[n][m]; int count = 0; // LOOP FOR GRID for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { if (grid[i][j] && !visited[i][j]) { numIslandsDFS(grid, visited, i, j); count++; } } } System.out.println(count); } /** * * @param grid * @param visited * @param x * @param y */ public void numIslandsDFS(boolean[][] grid, boolean[][] visited, int x, int y) { if (x < 0 || x >= grid.length) { return; } if (y < 0 || y >= grid[0].length) { return; } if (grid[x][y] != true || visited[x][y]) { return; } visited[x][y] = true; // Recursive call numIslandsDFS(grid, visited, x - 1, y); numIslandsDFS(grid, visited, x + 1, y); numIslandsDFS(grid, visited, x, y - 1); numIslandsDFS(grid, visited, x, y + 1); }}

 

点评

本质是求矩阵中连续区域的个数,很容易想到需要用深度优先搜索 DFS 来解,我们需要建立一个 visited 数组用来记录某个位置是否被访问过,对于一个为 true 且未被访问过的位置,我们递归进入其上下左右位置上为 true 的数,将其 visited 对应值赋为 true,继续进入其所有相连的邻位置,这样可以将这个连通区域所有的数找出来,并将其对应的 visited 中的值赋 true,找完次区域后,我们将结果 res 自增 1,然后我们在继续找下一个为 true 且未被访问过的位置,以此类推直至遍历完整个原数组即可得到最终结果。

这里需要有一个递归的调用。在递归调用之前需要进行判断是否超出边际,如果超出边际的话,就要跳出循环。

在一个节点进行遍历的时候,需要在递归调用的时候,同时针对这个节点搜索上下左右 4 个节点,如果找到需要了满足条件的 true,就继续查找,如果没有找到就退出。在这个过程的时候,需要将访问过的节点保存到访问控制的 2 维数组中。以便于在下次查找的时候跳过这个节点。

转载于:https://my.oschina.net/u/2344080/blog/2989057

你可能感兴趣的文章
超棒的CSS开源UI界面元素类库 - TopCat
查看>>
javaExecutors并发线程池ThreadPoolExecuto
查看>>
坦克大战源码
查看>>
不限量的快递查询接口-JAVA对接方法
查看>>
jib自定义entrypoint
查看>>
掌握Beyond Compare比较表格技巧
查看>>
图书资源下载网站推荐
查看>>
fastjson 总结
查看>>
介绍遍历子表的方法
查看>>
网络的分类
查看>>
PGSQL创建自增的id-- postgresql nextval 使用
查看>>
12python程序另一种运行方式
查看>>
Tomcat高级应用(添加虚拟主机及优化)
查看>>
Kindeditor(jsp)与SSH三大框架整合上传图片出错问题解决方案
查看>>
eyoucms网站基本信息设置
查看>>
如何优雅地实现分页查询
查看>>
常用安装rpm包--必备命令
查看>>
表单验证 018
查看>>
Java字节码3-使用ByteBuddy实现一个Java-Agent
查看>>
程序有没有可能输出y=2而x!=1的情况?如果可能,x可能会是什么值?如果不可能,为什么?...
查看>>