- 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