BOJ - 14940 - 쉬운 최단거리
Updated:
import sys
from collections import deque
dx = [0, 1, 0, -1]
dy = [1, 0, -1, 0]
def BFS(matrix, i, j, N, M):
dq = deque()
dq.append((i, j))
while dq:
x, y = dq.popleft()
for k in range(4):
nx, ny = x + dx[k], y + dy[k]
if 0 <= nx < N and 0 <= ny < M and matrix[nx][ny] == 1:
dq.append((nx, ny))
matrix[nx][ny] = matrix[x][y] + 1
def solution():
N, M = map(int, sys.stdin.readline().split())
matrix = []
for _ in range(N):
matrix.append(list(map(int, sys.stdin.readline().split())))
x, y = -1, -1
for i in range(N):
for j in range(M):
if matrix[i][j] == 2:
x, y = i, j
BFS(matrix, x, y, N, M)
for i in range(N):
for j in range(M):
v = matrix[i][j]
print("%d" % (v - 2 if v else 0), end=' ')
print()
solution()
https://www.acmicpc.net/problem/14940
Leave a comment