๋ฌธ์
๋ฐฑ์ค ์จ๋ผ์ธ ์ ์ง - 14940๋ฒ
ํ์ด ๊ณผ์
๋ชฉํ์ง์ ์ ๋๋ฌํ๊ธฐ ์ํ ์ต๋จ๊ฑฐ๋ฆฌ๋ฅผ ๊ตฌํ๋ ๋ฌธ์ ์
๋๋ค.
2์ฐจ์ ๋ฐฐ์ด์ ๊ฐ ์นธ์ ์ ์ ์ด๋ผ๊ณ ์๊ฐํ ๊ฒฝ์ฐ ๋ชจ๋ ์ธ์ ํ ์ ์ ๊น์ง์ ๊ฑฐ๋ฆฌ ๊ฐ์ ๊ฐ๊ธฐ ๋๋ฌธ์BFS
๋ฅผ ์ด์ฉํด์ ๋ชฉํ์ง์ ๊น์ง์ ์ต๋จ ๊ฑฐ๋ฆฌ๋ฅผ ๊ตฌํ ์ ์์ต๋๋ค.
์ฝ๋
import sys
from collections import deque
dx = [0, 0, 1, -1]
dy = [1, -1, 0, 0]
def find_start():
for x in range(N):
for y in range(M):
if board[x][y] == 2:
return [x, y]
def in_range(x, y):
return 0 <= x < N and 0 <= y < M
def bfs(sx, sy):
visit = [[-1] * M for _ in range(N)]
q = deque()
visit[sx][sy] = 0
q.append([sx, sy])
while q:
x, y = q.popleft()
for i in range(4):
nx, ny = x + dx[i], y + dy[i]
if in_range(nx, ny) and visit[nx][ny] == -1 and board[nx][ny]:
visit[nx][ny] = visit[x][y] + 1
q.append([nx, ny])
for x in range(N):
for y in range(M):
if board[x][y] == 0:
visit[x][y] = 0
return visit
def solution():
sx, sy = find_start()
dist = bfs(sx, sy)
for x in range(N):
print(' '.join(map(str, dist[x])))
if __name__ == '__main__':
N, M = list(map(int, sys.stdin.readline().split()))
board = [list(map(int, sys.stdin.readline().split())) for _ in range(N)]
solution()
๋ฐ์ํ
'๐ algorithm > boj' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
BOJ 10472 - ์ญ์๋ค์ง๊ธฐ (0) | 2021.04.18 |
---|---|
BOJ 13908 - ๋น๋ฐ๋ฒํธ (0) | 2021.04.13 |
BOJ 16441 - ์๊ธฐ๋ผ์ง์ ๋๋ (0) | 2021.04.13 |
BOJ 1922 - ๋คํธ์ํฌ ์ฐ๊ฒฐ (0) | 2021.04.13 |
BOJ 20006 - ๋ญํน์ ๋๊ธฐ์ด (0) | 2021.04.13 |
๐ฌ ๋๊ธ