[๋ฐฑ์ค€-7576] ํ† ๋งˆํ†  / Python

๐Ÿ“š Problem Solving/Baekjoon

https://www.acmicpc.net/problem/7576

 

7576๋ฒˆ: ํ† ๋งˆํ† 

์ฒซ ์ค„์—๋Š” ์ƒ์ž์˜ ํฌ๊ธฐ๋ฅผ ๋‚˜ํƒ€๋‚ด๋Š” ๋‘ ์ •์ˆ˜ M,N์ด ์ฃผ์–ด์ง„๋‹ค. M์€ ์ƒ์ž์˜ ๊ฐ€๋กœ ์นธ์˜ ์ˆ˜, N์€ ์ƒ์ž์˜ ์„ธ๋กœ ์นธ์˜ ์ˆ˜๋ฅผ ๋‚˜ํƒ€๋‚ธ๋‹ค. ๋‹จ, 2 ≤ M,N ≤ 1,000 ์ด๋‹ค. ๋‘˜์งธ ์ค„๋ถ€ํ„ฐ๋Š” ํ•˜๋‚˜์˜ ์ƒ์ž์— ์ €์žฅ๋œ ํ† ๋งˆํ† 

www.acmicpc.net

from collections import deque

n, m = map(int, input().split())
graph = []
for _ in range(m):
    graph.append(list(map(int, input().split())))
dx = [-1, 1, 0, 0]
dy = [0, 0, -1, 1]
queue = deque()


def bfs():
    while queue:
        x, y = queue.popleft()
        for i in range(4):
            nx = x + dx[i]
            ny = y + dy[i]
            if nx < 0 or ny < 0 or nx >= m or ny >= n:
                continue
            if graph[nx][ny] == 0:
                graph[nx][ny] = graph[x][y] + 1
                queue.append((nx, ny))


for i in range(m):
    for j in range(n):
        if graph[i][j] == 1:
            queue.append((i, j))

bfs()

isTrue = False
answer = -2
for i in graph:
    for j in i:
        if j == 0:
            isTrue = True
        answer = max(answer, j)
if isTrue == True:
    print(-1)
else:
    print(answer - 1)

ํ•ด์„ค

์•Œ๊ณ ๋ฆฌ์ฆ˜ ๋ฌธ์ œ๋ฅผ ํ•ด๊ฒฐํ•  ๋•Œ ์ œ์ผ ์žฌ๋ฐŒ๋Š” ํŒŒํŠธ๊ฐ€ BFS ๋ฌธ์ œ๋‹ค.

ํ† ๋งˆํ† ๊ฐ€ ์žˆ๋Š” ์œ„์น˜๋“ค์„ ๋จผ์ € deque์— ์ €์žฅํ•˜๊ณ  ๋‚˜์„œ BFS๋ฅผ ์ˆ˜ํ–‰ํ•œ๋‹ค. ์ฒ˜์Œ์—” ์ด ๋ถ€๋ถ„์„ ์บ์น˜ํ•˜์ง€ ๋ชปํ•ด์„œ ํ‹€๋ ธ๋‹ค..๐Ÿ˜…

ํ† ๋งˆํ† ๊ฐ€ ์žˆ๋Š” ์œ„์น˜๋กœ๋ถ€ํ„ฐ ์ ์  ํผ์ ธ๋‚˜๊ฐ€๋ฉด์„œ ์ต์€ ํ† ๋งˆํ† ๊ฐ€ ์ƒ๊ธฐ๊ธฐ ๋•Œ๋ฌธ์— ๋ฏธ๋ฆฌ deque์— ์ต์€ ํ† ๋งˆํ†  ์œ„์น˜๋ฅผ ์ €์žฅํ•ด์•ผ ํ•œ๋‹ค.

BFS๋ฅผ ๋ชจ๋‘ ์ˆ˜ํ–‰ํ•˜๊ณ  ๋‚˜์„œ graph ๋ฆฌ์ŠคํŠธ์— 0์ด ์žˆ์œผ๋ฉด ์•ˆ์ต์€ ํ† ๋งˆํ† ๊ฐ€ ์žˆ๋Š” ๊ฒƒ์ด๋ฏ€๋กœ flag๋ฅผ True๋กœ ํ•˜๊ณ  -1์„ ์ถœ๋ ฅํ•œ๋‹ค. ํ† ๋งˆํ† ๊ฐ€ ์ „๋ถ€ ์ต์—ˆ๋‹ค๋ฉด graph ๋ฆฌ์ŠคํŠธ์˜ ์ตœ๋Œ“๊ฐ’ - 1์„ ์ถœ๋ ฅํ•œ๋‹ค