Leetcode: Number of Islands
2015-08-25 10:13
260 查看
Question
Given a 2d grid map of ‘1’s (land) and ‘0’s (water), count the number of islands. An island is surrounded by water and is formed by connecting adjacent lands horizontally or vertically. You may assume all four edges of the grid are all surrounded by water.Example 1:
11110
11010
11000
00000
Answer: 1
Example 2:
11000
11000
00100
00011
Answer: 3
Credits:
Special thanks to @mithmatt for adding this problem and creating all test cases.
Show Tags
Show Similar Problems
Solution
Analysis
refer to GeeksforGeeks.“Quotation
This is an variation of the standard problem: “Counting number of connected components in a undirected graph”
“
The code is from 西施豆腐渣.
Code
[code]class Solution(object): def numIslands(self, grid): """ :type grid: List[List[str]] :rtype: int """ if grid==[]: return 0 row, col = len(grid), len(grid[0]) count = 0 for r in range(row): for c in range(col): if grid[r][c]=='1': self.search(grid, r, c) count += 1 return count def search(self, grid, r, c): if r<0 or r>=len(grid) or c<0 or c>=len(grid[0]) or grid[r][c]=='0': return grid[r][c] = '0' self.search(grid, r-1, c) self.search(grid, r+1, c) self.search(grid, r, c+1) self.search(grid, r, c-1)
相关文章推荐
- 前端图片延迟加载详细讲解
- JavaScript DOM
- 浅克隆与深克隆
- Validform的基本使用-表单校验
- 控制反转与依赖注入
- 在OnPaint中必须调用一次BeginPaint和EndPaint,且也只能调用一次
- java.lang.NoClassDefFoundError:的处理
- 动作游戏慢动作
- IOS上AudioSession设置, 切换扬声器和听筒详解
- 面试题23从上往下打印二叉树
- Deep Learning(深度学习)学习笔记整理系列之(五)
- POJ 1080 Human Gene Functions(DP LCS)
- USB驱动程序分析
- light oj 1032(数位DP)
- 微软牛津项目人脸识别API初探
- Android自定义对话框(Dialog)位置,大小
- Android中的动画,属性动画
- UGUI(八)UI节点制作
- Algorithms—230.Kth Smallest Element in a BST
- VC多线程--在线程之间传递窗口句柄是安全的