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