๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
๐Ÿƒ algorithm/boj

BOJ 14940 - ์‰ฌ์šด ์ตœ๋‹จ๊ฑฐ๋ฆฌ

by HandHand 2021. 4. 13.

๋ฌธ์ œ

๋ฐฑ์ค€ ์˜จ๋ผ์ธ ์ €์ง€ - 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()
๋ฐ˜์‘ํ˜•

๐Ÿ’ฌ ๋Œ“๊ธ€