https://www.acmicpc.net/problem/14940
2를 기준으로 거리를 적어야 하기 때문에 BFS를 생각했다.
문제를 풀며 깨달은 점
from sys import stdin
from collections import deque
input = stdin.readline
def bfs(s, d):
next_stack = set([])
while s:
tmp = s.pop()
g[tmp[0]][tmp[1]] = d
visited[tmp[0]][tmp[1]] = 1
for i in range(4):
next = (tmp[0] + y[i], tmp[1] + x[i]) # y,x
if next[0] >= n or next[0] < 0:
continue
if next[1] >= m or next[1] < 0:
continue
if g[next[0]][next[1]] == 0 or visited[next[0]][next[1]] == 1:
continue
next_stack.add(next)
if next_stack:
bfs(next_stack, d + 1)
n, m = map(int, input().split()) # 세로, 가로
g = []
for i in range(n):
g.append(list(map(int, input().split())))
visited = [[0 for _ in range(m)] for _ in range(n)]
t = 0
for i in range(n):
for j in range(m):
if g[i][j] == 2:
t = (i, j) # y,x
break
d = 0
stack = set([])
stack.add(t)
x = [0, 0, -1, 1]
y = [1, -1, 0, 0]
bfs(stack, 0)
for i in range(n):
for j in range(m):
if visited[i][j] == 0 and g[i][j] != 0:
g[i][j] = -1
for i in range(n):
for j in range(m):
print(g[i][j], end=" ")
print("")
채점결과 : 720ms
채점 결과 : 51660KB