Notice
Recent Posts
Recent Comments
05-21 07:17
«   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

미로찾기 - bfs 본문

Programming Language/Python

미로찾기 - bfs

알 수 없는 사용자 2022. 9. 2. 19:16
from collections import deque

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

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

visited = [[False]*5 for _ in range(5)]
path = deque()

def solution(graph, visited, x, y) :
	visited[y][x] = True
    path = deque([[x, y]])
    
    while path :
        x, y = path.popleft()
        for i in range(4) :
            pos1, pos2 = x+dx[i], y+dy[i]
            if 0<=pos1<5 and 0<=pos2<5 and not visited[pos2][pos1] and graph[pos2][pos1] :
                visited[pos2][pos1] = visited[y][x]+1
                path.append([pos1, pos2])

if __name__=="__main__" :
    solution(graph, visited, 0, 0)
    
    for i in visited :
        print(*i)
Comments