Closed chengchengxu15 closed 3 years ago
same as 200, just need to delete the lands in sides. https://github.com/chengchengxu15/leet_code/issues/46 3 solutions.
my solution:
class Solution:
def closedIsland(self, grid: List[List[int]]) -> int:
m = len(grid)
if m == 0:return 0
n = len(grid[0])
res = 0
def delete_one_land(cell,grid,m,n):
list_cell_for_this_land = [cell]
while list_cell_for_this_land:
cell = list_cell_for_this_land.pop()
i,j = cell
if grid[i][j] == 1:
continue
grid[i][j] = 1
if i > 0 and grid[i-1][j] == 0:list_cell_for_this_land.append((i-1,j))
if j > 0 and grid[i][j-1] == 0:list_cell_for_this_land.append((i,j-1))
if i < m-1 and grid[i+1][j] == 0:list_cell_for_this_land.append((i+1,j))
if j < n-1 and grid[i][j+1] == 0:list_cell_for_this_land.append((i,j+1))
for i in (0,m-1):
for j in range(n):
if grid[i][j] == 0:
cell = (i,j)
delete_one_land(cell,grid,m,n)
for j in (0,n-1):
for i in range(1,m-1):
if grid[i][j] == 0:
cell = (i,j)
delete_one_land(cell,grid,m,n)
for i in range(1,m-1):
for j in range(1,n-1):
if grid[i][j] == 0:
res +=1
cell = (i,j)
delete_one_land(cell,grid,m,n)
return res
leetcode:
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.