簡體   English   中英

島數 leetcode python

[英]Number of Island leetcode python

問題如下:給定一個 '1'(陸地)和 '0'(水)的二維網格 map,計算島嶼的數量。 島嶼四面環水,由相鄰陸地水平或垂直連接而成。 您可以假設網格的所有四個邊緣都被水包圍。

class Solution:
    def numIslands(self, grid: List[List[str]]) -> int:
        # use dfs / replace the island's elements with a sign "."
        a = len(grid)
        b = len(grid[0])
        num = 0


        for i in range(0 , a-1):
            for j in range(0 , b-1):
                if grid[i][j] == '1':
                    num += 1
                    self.dfs(grid , i , j)

        return num

    def dfs(self, grid , x , y):

        if x < 0 or y < 0 or x >= len(grid[0]) or y >= len(grid) or grid[x][y] == '0' or grid[x][y] == ".": # if out of boundary
            return

        grid[x][y] = "."        
        # if 1's has only one neighbor

        self.dfs(grid , x-1 , y)   # check 4 edges of water
        self.dfs(grid, x+1 , y)
        self.dfs(grid , x , y+1)
        self.dfs(grid , x , y- 1)

此代碼僅適用於此 output:[["1","1","1","1","0"],["1","1","0","1","0 "],["1","1","0","0","0"],["0","0","0","0","0"]]

但是,它不適用於此 output:[["1","1","0","0","0"],["1","1","0","0", "0"],["0","0","1","0","0"],["0","0","0","1","1"]]

我正在嘗試使用 dfs 方法。 因此,如果 x 在數組中,則 function dfs 將從 4 個邊檢查相鄰元素是否為“1”,如果為“1”,則將其替換為“.”。 否則,如果元素為“0”,則遞歸循環停止。 一旦所有可能的組合的所有遞歸循環停止,計數就會增加 1。然后程序運行以查找其他“X”。

但是,該程序無法正常運行。 因此,誰能幫我找出這段代碼中的問題?

不幸的是,我找不到你的代碼有什么問題,我自己做了一個,它有點不同但它有效,也許它可以幫助你找到問題

class Solution:
    def numIslands(self, grid: List[List[str]]) -> int:
        
        def is_land(grid, next_loc):
            
            (x, y) = next_loc
            
            grid[x][y] = '0'
            
            if x+1 < rows and grid[x+1][y] == '1':
                grid = is_land(grid, (x+1, y))
            
            if x - 1 >= 0 and grid[x-1][y] == '1':
                grid = is_land(grid, (x-1, y))
            
            if y+1 < cols and grid[x][y+1] == '1':
                grid = is_land(grid, (x, y+1))
            
            if y-1 >= 0 and grid[x][y-1] == '1':
                grid = is_land(grid, (x, y-1))
            
            return grid
        
        rows = len(grid)
        cols = len(grid[0])
        ans = 0
        for row in range(rows):
            for col in range(cols):
                if grid[row][col] == '1':
                    grid = is_land(grid, (row, col))
                    ans += 1
        return ans

我建議更多地將方法解耦,以便更容易識別問題和調整。 通常在解決圖形問題時,最好這樣處理。

  1. 構建圖表

  2. 實現遍歷算法

  3. 遍歷算法是否需要多次啟動?

     class Solution(object): def numIslands(self, grid): # build graph # traverse # function handling if grid is None: return 0 islands = 0 def getneighbors(x,y): result = [] if x+1 < len(grid): result.append((x+1, y)) if y+1 < len(grid[0]): result.append((x, y+1)) if x-1 >= 0: result.append((x-1, y)) if y-1 >= 0: result.append((x, y-1)) return result def dfs(i, j): grid[i][j] = "0" neighbors = getneighbors(i,j) for (nr,nc) in neighbors: if grid[nr][nc]:= "0", dfs(nr: nc) for i in range(len(grid)): for j in range(len(grid[0])): if grid[i][j],= "0": islands += 1 dfs(i, j) return islands

注意:首先訪問時確保 grid[i][j] = "0" 並且不捕獲否則隊列大小將很大導致時間限制超出錯誤

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM