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

本题使用DFS或者BFS都可以。

Solution. 1 DFS.

 class Solution(object):

     def numIslands(self, grid):
"""
:type grid: List[List[str]]
:rtype: int
"""
m = len(grid)
if m == 0:
return 0
n = len(grid[0]) ans = 0
for i in range(m):
for j in range(n):
if grid[i][j] == '':
ans += 1
self.helper(grid, m, n, i, j) return ans def helper(self, grid, m, n, i, j):
if (i < 0 or j < 0 or i > m-1 or j > n-1):
return if grid[i][j] == '':
grid[i][j] = ''
self.helper(grid, m, n, i-1, j)
self.helper(grid, m, n, i+1, j )
self.helper(grid, m, n, i, j-1)
self.helper(grid, m, n, i, j+1)

Solution. 2 BFS

 class Solution(object):
def numIslands(self, grid):
"""
:type grid: List[List[str]]
:rtype: int
"""
m = len(grid)
if m == 0:
return 0
n = len(grid[0])
visited = [ [False]* n for x in range(m)]
ans = 0
for i in range(m):
for j in range(n):
if grid[i][j] == '' and visited[i][j] == False:
ans += 1
self.bfs(grid, visited, m, n, i, j) return ans def bfs(self, grid, visited, m, n, i, j):
direct = [[0,1],[0,-1],[1,0],[-1,0]]
queue = [[i, j]]
visited[i][j] = True while queue:
front = queue.pop(0)
for p in direct:
np = [front[0]+p[0], front[1]+p[1]]
if self.isValid(np, m, n) and grid[np[0]][np[1]] == ''\
and visited[np[0]][np[1]] == False:
visited[np[0]][np[1]] = True
queue.append(np) def isValid(self, np, m, n):
return np[0]>=0 and np[0]<m and np[1]>=0 and np[1]<n

最新文章

  1. FineReport如何用JDBC连接阿里云ADS数据库
  2. 如何:加载分页结果(WCF 数据服务)
  3. 51单片机tea5767收音机 红外遥控 自动搜台 存台 DIY
  4. linux中的进程和线程
  5. php中simplexml_load_string使用实例
  6. CSS学习备忘
  7. 11个显著提升 ASP.NET 应用程序性能的技巧——第1部分
  8. vivado中使用MMCM ip核
  9. 模型压缩,模型减枝,tf.nn.zero_fraction,统计0的比例,等。
  10. 搭建简易的WebServer(基于pyhton实现简易Web框架 使用socket套接字)
  11. C++程序设计方法4:成员函数模板
  12. python类型错误:&#39;NoneType&#39; object is not subscriptable
  13. [Aaronyang] 写给自己的WPF4.5 笔记16[多线程]
  14. [记录] CSS 左边元素定长,右边元素获得剩余长度
  15. dotTrace 每行执行时间和执行次数
  16. Matlab 2016b 正式版下载
  17. 【bzoj3028】 食物 生成函数+隔板法
  18. Java IO:BIO和NIO差别及各自应用场景
  19. Mac下Python与Kafka的配合使用
  20. git看不到别人创建的远程分支

热门文章

  1. SQL Server 安装 功能详解
  2. java script 确认框
  3. 推薦使用 Microsoft Anti-Cross Site Scripting Library V3.0
  4. Linux 进程详解
  5. 关于lazyload插件的一些笔记
  6. 高性能JavaScript 达夫设备
  7. winform程序自动升级
  8. Android之捕获TextView超链接
  9. 3DMax 常用快捷键
  10. Excel——将内容导入