1254. Number of Closed Islands
- Number of Closed Islands python solution
题目描述
Given a 2D grid consists of 0s (land) and 1s (water). An island is a maximal 4-directionally connected group of 0s and a closed island is an island totally (all left, top, right, bottom) surrounded by 1s.
Return the number of closed islands.
解析
使用深度优先遍历,对逐个连通的小岛进行遍历,每次遍历后将小岛的值更改为-1,为防止重复遍历。
分别从四个角开始,对整个珊格的小岛进行遍历。
然后统计走不到的小岛的个数(即0的个数),这些小岛就属于被孤立的小岛。
if grid[i][j]==0:
dfs(i,j,-1)
res+=1
但是针对example1的情况,出现大量互相连通孤立小岛,在找到其中一个小岛后,需要在对小岛进行连通遍历,避免重复计数。上述代码
class Solution:
def closedIsland(self, grid: List[List[int]]) -> int:
if not grid:
return 0
m,n=len(grid),len(grid[0])
def dfs(i,j,val):
if(0<=i<m and 0<=j<n and grid[i][j]==0):
grid[i][j]=val
dfs(i+1,j,-1)
dfs(i-1,j,-1)
dfs(i,j+1,-1)
dfs(i,j-1,-1)
for i in range(m):
for j in range(n):
if(i==0 or i==m-1 or j==0 or j==n-1) and grid[i][j]==0:
dfs(i,j,-1)
res=0
for i in range(m):
for j in range(n):
if grid[i][j]==0:
dfs(i,j,-1)
res+=1
return res
Reference
https://leetcode.com/problems/number-of-closed-islands/discuss/425122/Python-easy-understand-DFS-solution
https://blog.csdn.net/fuxuemingzhu/article/details/81126995