zoukankan      html  css  js  c++  java
  • leetcode-mid-Linked list- 200. Number of Islands¶

    mycode  57.92%

    class Solution(object):
        def numIslands(self, grid):
            """
            :type grid: List[List[str]]
            :rtype: int
            """
            def recursive(i,j,row,col):
                if i>=0 and i<row and j>=0 and j<col:
                    if grid[i][j] == '0':
                        return 
                    grid[i][j] = '0'
                    if i-1 >= 0:
                        recursive(i-1,j,row,col)
                    if i+1 < row:
                        recursive(i+1,j,row,col)
                    if j-1 >= 0:
                        recursive(i,j-1,row,col)
                    if j+1 <= col:
                        recursive(i,j+1,row,col)
                else:
                    return 
            if not grid:
                return 0
            row = len(grid)
            col = len(grid[0])
            for i in range(row):
                for j in range(col):
                    if grid[i][j] == '1':
                        #print('if..',grid)
                        recursive(i,j,row,col)
                        grid[i][j] = '1'
                        #print('if..',grid)
            count = 0 
            for i in range(row):
                for j in range(col):
                    if grid[i][j] == '1':
                        count += 1
            return count

    参考:

    思路:其实第二次双层for循环是多余的,可以在前面就计数

    class Solution:
        def numIslands(self, grid):
            """
            :type grid: List[List[str]]
            :rtype: int
            """
            res = 0
            for r in range(len(grid)):
                for c in range(len(grid[0])):
                    if grid[r][c] == "1":
                        self.dfs(grid, r, c)
                        res += 1
            return res
            
        def dfs(self, grid, i, j):
            dirs = [[-1, 0], [0, 1], [0, -1], [1, 0]]
            grid[i][j] = "0"
            for dir in dirs:
                nr, nc = i + dir[0], j + dir[1]
                if nr >= 0 and nc >= 0 and nr < len(grid) and nc < len(grid[0]):
                    if grid[nr][nc] == "1":
                        self.dfs(grid, nr, nc)
  • 相关阅读:
    R语言基础入门
    调用arcpy包批量进行矢量掩膜提取
    一些js面试高频知识点的总结
    js实现五子棋人机对战源码
    编程题汇总,持续更新
    颜色字符串转换
    根据包名,在指定空间中创建对象
    JavaScript中[]+[] 、[]+{}、{}+[]、{}+{}的结果分析
    CSS命名规范
    谈谈浏览器的兼容性
  • 原文地址:https://www.cnblogs.com/rosyYY/p/10969281.html
Copyright © 2011-2022 走看看