본문 바로가기

카테고리 없음

[1일1알고리즘] 4.30일 금요일 미로 찾기 BFS

from collections import deque

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



def solution(maps):
    graph = maps
    n = len(graph[0])
    m = len(graph)

    def bfs(x,y) :
        queue = deque()
        queue.append((x,y))
        while queue : 
            x, y = queue.popleft()
            for i in range(4) :
                nx = x + dx[i]
                ny = y + dy[i]
                if nx < 0 or ny < 0 or nx >= n or ny >= m : 
                    continue
                if graph[nx][ny] == 0 :
                    continue
                if graph[nx][ny] == 1:
                    graph[nx][ny] = graph[x][y] + 1
                    queue.append((nx,ny))
        result = graph[n-1][m-1]

        if result  == 1 : 
            return -1
        else : 
            return result
    return bfs(0,0)