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!

  • 相关阅读:
    1049.(*) Counting Ones
    1135(重、错)Is It A Red-Black Tree
    3、如何判断一棵树是否是红黑树?
    2、以自定义struct或struct指针作为map的Key
    1、(★、※)如何判断一棵树是否是完全二叉树?
    1123.(重、错)Is It a Complete AVL Tree
    160819流水账
    150819流水账
    140819流水账
    130819流水账
  • 原文地址:https://www.cnblogs.com/wangyuxia/p/14580480.html
Copyright © 2011-2022 走看看