• 카테고리

    질문 & 답변
  • 세부 분야

    알고리즘 · 자료구조

  • 해결 여부

    미해결

DFS 에러가 납니다

22.05.13 22:59 작성 조회수 345

0

안녕하세요 강사님

DFS 로 풀어 보았는데 RecursionError: maximum recursion depth exceeded in comparison 에러가 뜹니다.

어느 부분이 문제일까요? 제가 비교해보니 강사님과 전체적인 구조는 똑같이 푼 것 같은데 자꾸 오류가 납니다. ㅠㅠ

 

def dfs(x, y, h):
    visited[i][j] = 1

    for k in range(4):
        xx = x + dx[k]
        yy = y + dy[k]
        if 0 <= xx < n and 0 <= yy < n:
            if visited[xx][yy] == 0 and graph[xx][yy] > h:
                dfs(xx, yy, h)


n = int(input())
graph = [list(map(int, input().split())) for _ in range(n)]

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

mmax = -2147000000
for i in range(n):
    for j in range(n):
        if graph[i][j] > mmax:
            mmax = graph[i][j]

cnt = 0
res = 0
for h in range(100):  # 높이가 100 이면 안전영역은 0개이기 때문에 할 필요 X
    if h > mmax:
        break
    cnt = 0
    visited = [[0] * n for _ in range(n)]
    for i in range(n):
        for j in range(n):
            if visited[i][j] == 0 and graph[i][j] > h:
                cnt += 1
                dfs(i, j, h)

    res = max(res, cnt)
print(res)

답변 1

답변을 작성해보세요.

0

안녕하세요^^

재귀가 너무 많이 돌아서 그런 것 같습니다. 아래 코드를 넣어 보세요.

import sys sys.setrecursionlimit(10**5)

깨위님의 프로필

깨위

2023.01.22

안녕하세요!

재귀가 많이 돌아, 스택이 가득 차면.. 실제 코딩 테스트에서는 BFS로 풀어야 하나요?

아니면

import sys sys.setrecursionlimit(10**5)를 붙여야 하나요?