岛屿的个数
来源:互联网 发布:淘宝店家投诉 编辑:程序博客网 时间:2024/04/30 03:25
题目描述:给一个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 个岛.
我们现在把目光聚焦到其中一个1上,从这个1开始,先将这个1改成0,再沿着上下左右4个方向开始遍历矩阵,遍历的方法是深度优先搜索(详见:点击打开链接),将所有遍历到的1都改成0,直到在一个1的四个方向上相邻的的元素都是0,那么停止对这个元素的深搜。这样,我们就将“一个岛屿”上的所有1都改成了0,从地图上看,这个岛屿“消失了”。那么有多少个岛屿呢?就看这样的深搜遍历有多少次(因为一次这样的深搜消去了一个岛屿),代码如下:
class Solution: # @param {boolean[][]} grid a boolean 2D matrix # @return {int} an integer def numIslands(self, grid): if len(grid) == 0 or len(grid[0]) == 0: return 0 index1, row = 0, len(grid) index2, col = 0, len(grid[0]) count = 0 # 二维矩阵的遍历 while index1 < row: index2 = 0 while index2 < col: if grid[index1][index2] == 1: self.dfs_helper(grid, index1, index2) count += 1 index2 += 1 index1 += 1 return count # 深搜函数 def dfs_helper(self, grid, i, j): # 终止条件 if i >= len(grid) or j >= len(grid[0]): return if grid[i][j] == 0: return # 1改成0 grid[i][j] = 0 # 沿4个方向深搜 if i < len(grid): self.dfs_helper(grid, i + 1, j) if j < len(grid[0]): self.dfs_helper(grid, i, j + 1) if j > 0: self.dfs_helper(grid, i, j - 1) if i > 0: self.dfs_helper(grid, i - 1, j) # Write your code here这道题关键是对深搜算法的熟悉程度,所以,没明白的话,请详细参考之前的讲解。
0 0
- 题目:岛屿的个数
- LintCode 岛屿的个数
- LinkCode-岛屿的个数
- 岛屿的个数
- 岛屿的个数
- 岛屿的个数-lintcode
- 岛屿的个数
- 岛屿的个数
- LintCode:岛屿的个数
- 433-岛屿的个数
- 岛屿的个数
- 岛屿的个数-LintCode
- 岛屿的个数(LintCode)
- LintCode 433. 岛屿的个数
- Java实现-岛屿的个数
- 岛屿个数
- Lintcode解题笔记 - 岛屿的个数
- LintCode——岛屿的个数
- pod repo
- android下的callback机制
- The Begining
- 页面置换算法整理
- android 加入第三方jar 编译错误
- 岛屿的个数
- stm32之EXTI中断
- html meta 直接跳转页面
- JQuery图表插件Flot之效果源码
- 变量和基本数据类型
- CentOS 6.5下搭建vsftp服务器
- ext6.0+cordova+android开发 第二章 入门
- 单分类
- 百度地图-修改marker图标(icon)及同时显示多点