• 200.岛屿数量 leetcode


    思路:  深度遍历

      1.第一层main函数里 两层循环找 grid[x][y] == '1' 的点 res += 1

      2.递归函数里,把与该点四个方向相邻的,值为‘1’的点全部标0

       标0方法: 对坐标(x,y)四个方向中 值 == ‘1’ 的赋0 再递归。

     

    注意:

      1. 对于二维数组,判空要用  if len( grid ) == 0: return 0

       我之前的错误用法是 if not grid: return 0   

       因为即使空的二维数组 也是 [ [  ] ]

     代码:

     

    class Solution:
        def numIslands(self, grid: List[List[str]]) -> int:
            
            def set_to_zero(row,col,grid):
                grid[row][col] = '0'
                dirs = [(row,col-1),(row-1,col),(row+1,col),(row,col+1)]
                nr = len(grid)
                nc = len(grid[0])
                for x,y in dirs:
                    if   0<=x<nr and 0<=y<nc and grid[x][y] == '1':
                        set_to_zero(x,y,grid)

            if not grid or len(grid[0]) == 0:
                return 0
            res = 0
            for i in range(len(grid)):
                for j in range(len(grid[0])):
                    if grid[i][j] == '1':
                        res+=1
                        set_to_zero(i,j,grid)
            return res



            



  • 相关阅读:
    jmeter接口测试二
    jmeter 插件入口
    Python正则匹配中的最小匹配和贪婪匹配
    python中的url编码和解码(encode与decode)乱码
    python2.7+pyqt+eric基本控件操作(制作界面化程序)
    python2.7+PyQt4+eric6 界面开发环境配置
    centos配置静态ip地址
    分片,步长,索引
    我看过的几本书籍
    软件测试工程师的成长之路(个人看法)
  • 原文地址:https://www.cnblogs.com/ChevisZhang/p/12881817.html
Copyright © 2020-2023  润新知