hugo-blog/content/posts/2020-04-21-leetcode-number-of-islands.md
Ching 5ba7024532 feat(content; layouts; static): migrate hexo blog. add new theme fuji.
migrate hexo blog. add new theme fuji.

Signed-off-by: Ching <loooching@gmail.com>
2022-02-07 23:38:40 +08:00

51 lines
1.2 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

---
title: leetcode-number-of-islands
date: 2020-04-21 12:55:17
tags:
- leetcode
categories: leetcode
---
### 200. 岛屿数量
[题目](https://leetcode-cn.com/problems/number-of-islands/)
<!--more-->
这种矩阵题现在第一反应就是用[广度优先搜索][0]做类似之前算和0之间的距离那题。遍历矩阵遇到 1 就将 1 改成 0然后广度优先搜索找出 1 相邻的所有 1这就是一个岛屿以此类推。
```python
import collections
class Solution:
def numIslands(self, grid) -> int:
rows = len(grid)
if not rows:
return 0
cols = len(grid[0])
islands = 0
for r in range(rows):
for l in range(cols):
if grid[r][l] == '1':
islands += 1
grid[r][l] = '0'
neighbors = collections.deque([(r, l)])
while neighbors:
x, y = neighbors.popleft()
for x_, y_ in [[x-1, y], [x+1, y], [x, y-1], [x, y+1]]:
if 0<=x_<rows and 0<=y_<cols and grid[x_][y_] == '1':
neighbors.append([x_, y_])
grid[x_][y_] = '0'
return islands
```
[0]:(https://zh.wikipedia.org/zh-cn/%E5%B9%BF%E5%BA%A6%E4%BC%98%E5%85%88%E6%90%9C%E7%B4%A2)