zoukankan      html  css  js  c++  java
  • 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!

  • 相关阅读:
    n皇后问题
    几种NFS系统对比,选型理由
    MooseFs集群故障恢复运维
    TB级NFS数据平滑迁移方案设计与实现
    NFS挂载各机显示用户不同的问题
    TB级NFS数据平滑迁移系列
    mysql备份和恢复
    Java基础赋值符号
    java 流程控制基础之if else
    Java基础赋值符号
  • 原文地址:https://www.cnblogs.com/wangyuxia/p/14580480.html
Copyright © 2011-2022 走看看