【重点】【DFS】1254.统计封闭岛屿的数目

题目

DFS

Python

思路:先外后内,先遍历边界,再处理内部!!!

class Solution:
    def closedIsland(self, grid: List[List[int]]) -> int:
        res = 0
        m, n = len(grid), len(grid[0])

        for i in range(m): # 先遍历边界0, 并置1
            for j in range(n):
                if (i == 0 or i == m-1 or j == 0 or j == n-1) and grid[i][j] == 0:
                    self.dfs(grid, i, j)

        for i in range(m): # 再遍历内部0, 都是封闭岛
            for j in range(n):
                if grid[i][j] == 0:
                    self.dfs(grid, i, j)
                    res += 1
        return res
    
    def dfs(self, grid, i, j):
        if (i < 0 or i >= len(grid) 
            or j < 0 or j >= len(grid[0])
            or grid[i][j] == 1):
            return
        grid[i][j] = 1
        self.dfs(grid, i-1, j)
        self.dfs(grid, i+1, j)
        self.dfs(grid, i, j+1)
        self.dfs(grid, i, j-1)
### Python DFS Algorithm Count Islands Implementation For the problem of counting islands using a depth-first search (DFS) algorithm in Python, an effective approach involves traversing through each cell within a grid. When encountering land (`'1'`), one initiates a DFS from that point and marks all connected parts as visited by setting them to water (`'0'`). This process continues until every part of this island is marked. Below demonstrates how such functionality can be implemented: ```python def numIslands(grid): if not grid or not grid[0]: return 0 rows, cols = len(grid), len(grid[0]) def dfs(r, c): if r < 0 or r >= rows or c < 0 or c >= cols or grid[r][c] == '0': return grid[r][c] = '0' directions = [(0, 1), (1, 0), (-1, 0), (0, -1)] for dr, dc in directions: dfs(r + dr, c + dc) count = 0 for row in range(rows): for col in range(cols): if grid[row][col] == "1": dfs(row, col) count += 1 return count ``` This function iterates over each element in `grid`. Upon finding `'1'`, it calls `dfs()` which recursively visits adjacent cells also containing `'1'`, changing their value to `'0'` so they won't be revisited later on during iteration. Each call to `dfs()` starting at unvisited land increments the total number of discovered islands[^1]. --related questions-- 1. How does marking visited nodes affect performance when implementing DFS? 2. Can BFS replace DFS effectively in solving the Island Count problem? What changes would occur? 3. In what scenarios might dynamic programming enhance solutions similar to counting islands? 4. Are there alternative methods besides modifying input data directly for tracking visited locations in grids?
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值