[LeetCode] 1254. Number of Closed Islands

김민우·2022년 12월 24일
0

알고리즘

목록 보기
97/189

- Problem

1254. Number of Closed Islands

- 내 풀이

LAND = 0
WATER = 1
VISITED = -1

class Solution:
    def closedIsland(self, grid: List[List[int]]) -> int:
        def bfs(y, x):
            q = collections.deque([[y, x]])
            grid[y][x] = VISITED
            is_closed = True

            while q:
                y, x = q.popleft()
                if y == 0 or y == M-1 or x == 0 or x == N-1:
                    is_closed = False
                
                for dx, dy in ((-1, 0), (1, 0), (0, -1), (0, 1)):
                    nx = x + dx
                    ny = y + dy

                    if 0 <= nx < N and 0 <= ny < M and grid[ny][nx] == LAND:
                        grid[ny][nx] = VISITED
                        q.append([ny, nx])

            return 1 if is_closed else 0

        M, N = len(grid), len(grid[0])

        closed_islands = 0

        for i in range(M):
            for j in range(N):
                if grid[i][j] == LAND:
                    closed_islands += bfs(i, j)

        return closed_islands

- 결과

profile
Pay it forward.

0개의 댓글