💡문제접근

  • 0-1 BFS 탐색 알고리즘을 이용해서 문제를 해결했다.
  • 관련 다른 문제들도 풀어보면서 0-1 BFS 탐색 알고리즘에 대해서 익숙해질 필요가 있을 것 같다.

💡코드(메모리 : 34184KB, 시간 : 80ms)

from collections import deque
import sys
input = sys.stdin.readline

M, N = map(int, input().strip().split())
maze = [list(map(int, input().strip())) for _ in range(N)]
distance_weight = [[-1] * M for _ in range(N)]

def BFS(a, b):
    queue = deque()
    queue.append((a, b))
    distance_weight[a][b] = 0
    while queue:
        x, y = queue.popleft()
        dx = [0, 1, 0, -1]
        dy = [-1, 0, 1, 0]
        for i in range(4):
            nx = x + dx[i]
            ny = y + dy[i]
            if nx < 0 or nx >= N or ny < 0 or ny >= M:
                continue
            if 0 <= nx < N and 0 <= ny < M:
                if distance_weight[nx][ny] == -1:
                    if maze[nx][ny] == 0:
                        queue.appendleft((nx, ny))
                        distance_weight[nx][ny] = distance_weight[x][y]
                    else:
                        queue.append((nx, ny))
                        distance_weight[nx][ny] = distance_weight[x][y] + 1
    return distance_weight[N-1][M-1]

print(BFS(0, 0))

💡소요시간 : 34m

0개의 댓글