LeetCode-200 岛屿的个数

1. 题目

深度优先搜索

https://leetcode-cn.com/problems/number-of-islands/

给定一个由 '1'(陆地)和 '0'(水)组成的的二维网格,计算岛屿的数量。一个岛被水包围,并且它是通过水平方向或垂直方向上相邻的陆地连接而成的。你可以假设网格的四个边均被水包围。

示例 1:

输入:
11110
11010
11000
00000

输出: 1

示例 2:

输入:
11000
11000
00100
00011

输出: 3

2. 我的AC

解题思路

  • 从最左上角开始遍历这个网格图
  • 当遍历到该点值为1的时候,将其更新为0
  • 并进行 dfs,把和它四联通的陆地(即值为1)全部更新为0,直到不能扩展
  • 所以,总的进行了dfs的次数,就是岛的数目。

注意理解 dfs 函数的意义:已知当前是1,把它周围相邻的所有1全部转成0

参考:https://blog.csdn.net/fuxuemingzhu/article/details/81126995

class Solution(object):
    def numIslands(self, grid):
        """
        :type grid: List[List[str]]
        :rtype: int
        """
        result = 0
        for r in range(len(grid)):
            for c in range(len(grid[0])):
                if grid[r][c] == '1': # 发现一个岛屿
                    result += 1
                    self.dfs(grid, r, c) # 把该岛屿全部标0
        return result
        
    def dfs(self, grid, i, j):
        grid[i][j] = '0'
        if i-1 >= 0 and grid[i-1][j] == '1':
            self.dfs(grid, i-1, j)
        if i+1 < len(grid) and grid[i+1][j] == '1':
            self.dfs(grid, i+1, j)                    
        if j-1 >= 0 and grid[i][j-1] == '1':
            self.dfs(grid, i, j-1)   
        if j+1 < len(grid[0]) and grid[i][j+1] == '1':
            self.dfs(grid, i, j+1)            

测试用例

List[List[str]]
[["1","1","1","1","0"],["1","1","0","1","0"],["1","1","0","0","0"],["0","0","0","0","0"]]

3. 小结

  1. 空列表无法索引 list[0]
  • 报错
grid = []
rows, cols = len(grid), len(grid[0])
for i in range(rows):
    for j in range(cols): 
        print i, j
# IndexError: list index out of range
  • 正常
grid = []

for i in range(len(grid)):
    for j in range(len(grid[0])):  # for j in range(False):
        print i, j

你可能感兴趣的:(LeetCode-200 岛屿的个数)