💡문제접근
- 출발점부터 도착점까지 이동할 때 지나야 하는 최소의 칸 수를 구하는 문제였는데
최소
에 꽂혀서 바로 BFS
로 접근했던 문제였다. 아직 BFS가 익숙하지 않아서 코드를 작성하는데 시간이 좀 걸렸다.
- 출발점에서부터 이동할 때 만약 이동 가능한 칸이라면 1만큼 더해 해당 칸으로 이동했다는 것을 표시했다.
💡코드(메모리 : 34104KB, 시간 : 72ms)
from collections import deque
import sys
N, M = map(int, input().split())
graph = []
for _ in range(N):
graph.append(list(map(int, sys.stdin.readline().strip())))
def BFS(graph, x, y):
queue = deque()
queue.append((x, y))
while queue:
dx = [0, 0, 1, -1]
dy = [1, -1, 0, 0]
x, y = queue.popleft()
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 and graph[nx][ny] == 1:
graph[nx][ny] = graph[x][y] + 1
queue.append((nx, ny))
return graph[N-1][M-1]
print(BFS(graph, 0, 0))
💡소요시간 : 51m