[알고리즘 문제 풀이] 미로 찾기

이동욱

2021/09/15

Categories: 알고리즘

문제 - 미로 탈출


제한 사항


코드


from collections import deque


def solution(n, m, graph):
    dx = [-1, 1, 0, 0]
    dy = [0, 0, -1, 1]

    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))
        return graph[n - 1][m - 1]

    return bfs(0, 0)


if __name__ == "__main__":
    n, m = map(int, input().split())

    graph = []
    for i in range(n):
        graph.append(list(map(int, input())))

    print(solution(n, m, graph))

배운점


참고 문헌


>> Home