Published:
Updated:

  • Reference
  • visited μ“°κ³  ν’€ μˆ˜λ„ μžˆλŠ” 문제


Solution

from typing import List


class Solution:
    # 섬 -> '0'(water)둜 λ‘˜λŸ¬μ‹Έμ—¬ μžˆμ–΄μ•Ό 함, 보이지 μ•ŠλŠ” λ°”κΉ₯은 μ „λΆ€ '0'이라고 κ°€μ •
    # "λŒ€κ°μ„ μ€ κ³ λ €ν•  ν•„μš”κ°€ μ—†μŒ"
    def numIslands(self, grid: List[List[str]]) -> int:
        WATER = '0'
        LAND = '1'

        # answer: μ„¬μ˜ 개수
        answer = 0
        # κΈ°λ³Έ x, y
        len_x = len(grid[0])
        len_y = len(grid)

        def dfs(x: int, y: int) -> None:
            if x < 0 or x >= len_x \
                    or y < 0 or y >= len_y \
                    or grid[y][x] == WATER:
                return

            # visited μ‚¬μš©ν•  수 μžˆμ§€λ§Œ κ³΅κ°„λ³΅μž‘λ„λ₯Ό μœ„ν•΄ 이 λ¬Έμ œμ—μ„œλŠ” '0'으둜 μ €μž₯
            grid[y][x] = WATER

            dfs(x + 1, y)
            dfs(x - 1, y)
            dfs(x, y + 1)
            dfs(x, y - 1)

        for y in range(len_y):
            for x in range(len_x):
                if grid[y][x] == LAND:
                    dfs(x, y)
                    answer += 1

        return answer

Leave a comment