Leetcode 200. Number of Islands

Description: Given an m x n 2D binary grid grid which represents a map of '1's (land) and '0's (water), return 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.

Link: 200. Number of Islands

Examples:

Example 1:
Input: grid = [
  ["1","1","1","1","0"],
  ["1","1","0","1","0"],
  ["1","1","0","0","0"],
  ["0","0","0","0","0"]
]
Output: 1

Example 2:
Input: grid = [
  ["1","1","0","0","0"],
  ["1","1","0","0","0"],
  ["0","0","1","0","0"],
  ["0","0","0","1","1"]
]
Output: 3

思路: 在题目中,岛屿被定义为连接在一起的一片"1",这里的连接就是上下左右有一个方向相通。有几个这样的片就有几个岛屿,遍历到 1 时,DFS找到所有相连的1,变成“0”(其他非1的字母数字也可以),DFS的次数就是岛屿数。

class Solution(object):
    def numIslands(self, grid):
        """
        :type grid: List[List[str]]
        :rtype: int
        """
        res = 0
        for i in range(len(grid)):
            for j in range(len(grid[0])):
                if grid[i][j] == "1":
                    self.dfs(i, j, grid)
                    res += 1
        return res
                    
    def dfs(self, i, j, grid):
        dirs = [(0,1), (0,-1), (1,0), (-1,0)]
        grid[i][j] = "0"
        for d in dirs:
            x = i + d[0]
            y = j + d[1]
            if x >=0 and x < len(grid) and y>=0 and y < len(grid[0]) and grid[x][y] == "1":
                self.dfs(x, y, grid)

日期: 2021-03-26 Focus on yourself,plz!

原文地址:https://www.cnblogs.com/wangyuxia/p/14580480.html