---
title: leetcode-number-of-islands
date: 2020-04-21 12:55:17
tags:
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)
