BOJ.14940

Opusdeisong·2023년 11월 26일
0

백준 Class3

목록 보기
9/14


#BOJ14940

쉬운 최단거리 문제

진짜 보자마자 와 전형적인 BFS 문제라는 것이 보였다. 해서 7576번 코드를 재활용해서 풀기로 하였다. 크게 설명할만한 부분이 없는 것 같아서 간단한 코드와 함께 글을 줄이겠다.

import sys
from collections import deque

N, M = map(int, sys.stdin.readline().split())
arr = [list(map(int, sys.stdin.readline().split())) for _ in range(N)]
queue = deque([])

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

for i in range(N):
   for j in range(M):
       if arr[i][j] == 2:
           queue.append([i, j])
while queue:
   x, y = queue.popleft()
   for i in range(4):
       xx, yy = dx[i] + x, dy[i] + y
       if 0 <= xx < N and 0 <= yy < M:
           if arr[xx][yy] == 1:
               arr[xx][yy] = arr[x][y] + 1
               queue.append([xx, yy])

for i in arr:
   for j in i:
       if j == 0:
           print(0, end=" ")
       elif j == 1:
           print(-1, end=" ")
       else:
           print(j - 2, end=" ")
   print()
profile
Dorsum curvatum facit informaticum.

0개의 댓글