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!

  • 相关阅读:
    java 生成随机字符串
    java 使用抽象工厂封装特性方法
    c3p0 连接池配置数据源
    sql 语法总结
    HttpRequestUtils post get请求
    Spring事务(1)
    Spring增强
    面试题
    Java的三种代理模式
    Spring中bean的作用域与生命周期
  • 原文地址:https://www.cnblogs.com/wangyuxia/p/14580480.html
Copyright © 2011-2022 走看看