4963 파이썬

Lee Hyun Joon ·2022년 7월 10일

알고리즘정리

목록 보기
5/17

4963번은 이전 지도 내의 dfs, bfs 방식에서 대각선의 옵션을 고려한 방법을 구현하면 된다.
하지만, 메모리 초과가 발생해서 바로 sys.setrecursionlimit 오류를 확인했다.
이 재귀 depth 설정은 크게 둘수록 좋다고 생각했었지만, 오히려 메모리 할당 후 메모리 초과 문제를 발생할 수도 있기에 적당한 값을 부여해야한다고 느낀 적이 있었다.

이번엔 수정할때 최대로 줘야할 depth의 크기에 대해 고민했다. 좌표에서 출발해서 8개의 방향이 있음과 동시에 5050칸이기에 8 2500 인 20000을 값으로 할당했다.
이 결과 메모리 초과가 나지 않아서 해결했다!
🙌 메모리 초과 시 recursionlimit도 생각하기! 🙌

import sys 
sys.setrecursionlimit(10**4)
dx=[1,-1,0,0,1,1,-1,-1]
dy=[0,0,1,-1,-1,1,-1,1]

def dfs(x,y,visited,map_loc):
    for i in range(8):
        x_t = x+ dx[i]
        y_t = y + dy[i]
        # print(visited) 
        # print(x_t, y_t)
        if (0<=x_t and x_t <len(map_loc)) and (0<=y_t and y_t<len(map_loc[0])) :
            if visited[x_t][y_t] == False and map_loc[x_t][y_t] == 1:
                visited[x_t][y_t] = True
                dfs(x_t,y_t,visited,map_loc)
while True:
    
    cnt = 0
    w, h = map(int, sys.stdin.readline().strip().split())
    if w==0 and h==0:
        break
    map_loc = []
    visited = []
    for i in range(h):
        map_loc.append(list(map(int,sys.stdin.readline().strip().split())))
        visited.append([False for _ in range(w)])
    # print(visited)
    for i in range(h):
        for j in range(w):
            if map_loc[i][j] == 1 and visited[i][j] == False:
                cnt +=1 
                visited[i][j] = True
                dfs(i,j,visited,map_loc)
    print(cnt)
profile
우당탕탕 개발 지망생

0개의 댓글