Problem Solving/LeetCode
2023.04.06 Today's Challenge
fabichoi
2023. 4. 6. 23:45
https://leetcode.com/problems/number-of-closed-islands/
Number of Closed Islands - LeetCode
Can you solve this real interview question? Number of Closed Islands - 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,
leetcode.com
DFS의 전형적인 문제
class Solution:
def closedIsland(self, grid: List[List[int]]) -> int:
rs, cs = len(grid), len(grid[0])
cnt = 0
def dfs(i, j):
if i < 0 or j < 0 or i >= rs or j >= cs:
return False
if grid[i][j] == 1:
return True
grid[i][j] = 1
left = dfs(i, j-1)
right = dfs(i, j+1)
up = dfs(i-1, j)
down = dfs(i+1, j)
return left and right and up and down
for i in range(rs):
for j in range(cs):
if grid[i][j] == 0 and dfs(i, j):
cnt += 1
return cnt
반응형