하루일문

[백준] 4963 섬의 개수(파이썬) 본문

algorithm/baekjoon

[백준] 4963 섬의 개수(파이썬)

support_u 2023. 2. 13. 16:09

풀이

import sys
sys.setrecursionlimit(10**6)
# 파이썬은 재귀 깊이가 정해져있어서 의도적으로 늘려주어야 합니다.


dx = [-1, -1, -1, 0, 0, 1, 1, 1]
dy = [-1, 0, 1, -1, 1, -1, 0, 1]

def dsf(graph, x, y, visit):
        # 8방향 반복
        for _ in range(8):
            nx = x + dx[_]
            ny = y + dy[_]
            # 표 안에 들어가면서 안 드린곳
            if 0 <= nx < h and 0 <= ny < w and graph[nx][ny] == 1 and visit[nx][ny] == False:
                visit[nx][ny] = True
                dsf(graph, nx, ny, visit)


while True:
    w, h = map(int, input().split())

    if w == 0 and h == 0:
        break

    island = [list(map(int, input().split())) for _ in range(h)]
    # 들린 곳 체크리스트
    visited = [[False] * w for _ in range(h)]

    cnt = 0
    for i in range(h):
        for j in range(w):
            # 1이면서 들리지 않은 곳 
            if island[i][j] == 1 and visited[i][j] == False:
                visited[i][j] = True
                dsf(island, i, j, visited)
                # 다녀왔다면 섬 1개
                cnt += 1

    print(cnt)

오류

런타임 에러 (RecursionError)

이유

재귀에 깊이를 늘려주지 않아서,
수가 크기 때문에 파이썬으로 문제를 풀기 위해서 재귀에 깊이를 정해주는게 필수이다
만약 틀린부분이 없으면 붙여보자!
import sys
sys.setrecursionlimit(10**6)