Notice
Recent Posts
Recent Comments
05-17 09:12
«   2024/05   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
Archives
Today
Total
관리 메뉴

Byeol Lo

미로찾기 - dfs 본문

Programming Language/Python

미로찾기 - dfs

알 수 없는 사용자 2022. 9. 2. 18:49

미로 문제가 나왔을때 다음과 같이 변수들을 선언하고 알고리즘을 짠다.

graph = [
    [1,1,1,0,1],
    [1,0,1,1,1],
    [1,1,1,0,1],
    [1,0,1,0,1],
    [1,1,1,1,1]
]

visited = [[False]*len(graph[0]) for _ in range(len(graph))]

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

def solution(graph, visited, x, y, walk) :
    
    if not visited[y][x] or visited[y][x] > walk :
        visited[y][x] = walk
    else :
        return
    
    for i in range(4) :
        pos1 = x+dx[i]
        pos2 = y+dy[i]
        # indexerror가 난다면 넘어가고
        # 안나면 graph에서 안막혀있을때 방문처리
        if 0 <= pos1 < 5 and 0 <= pos2 < 5 and graph[pos2][pos1] :
            solution(graph, visited, pos1, pos2, walk+1)

if __name__ == "__main__" :
    
    solution(graph, visited, 0, 0, 0)
    visited[0][0] = 0
    
    for i in visited :
        print(*i)
    
    print(f"result = {visited[-1][-1]}")
Comments