๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
4๏ธโƒฃ Python/Problem Solving

[Python Algorithm] ํ† ๋งˆํ†  BOJ #7576

by seolhee2750 2022. 1. 30.
๋ฌธ์ œ

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

 

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

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

www.acmicpc.net

 

๋‚ด ๋ฌธ์ œ ํ’€์ด
import sys, copy
m, n = map(int, sys.stdin.readline().split())
storage = [list(map(int, sys.stdin.readline().split())) for _ in range(n)]
queue = []
dx = [0, 0, -1, 1]
dy = [-1, 1, 0, 0]
countCheck = copy.deepcopy(storage)
result = 0
zero = False

def bfs(count):
    index = 0
    while len(queue) > index:
        x, y, n_count = queue[index][0], queue[index][1], queue[index][2]
        index += 1

        for i in range(4):
            nx = x + dx[i]
            ny = y + dy[i]

            if nx < 0 or ny < 0 or nx >= n or ny >= m: continue
            if storage[nx][ny] == 0:
                storage[nx][ny] = 1
                countCheck[nx][ny] = n_count+1
                queue.append((nx, ny, n_count+1))

for i in range(n):
    for j in range(m):
        if storage[i][j] == 1:
            queue.append((i, j, 0))
        if storage[i][j] == 0:
            zero = True

if zero == False:
    print(0)
else:
    bfs(0)
    for i in range(n):
        if 0 in storage[i]:
            result = -1
            break
        result = max(result, max(countCheck[i]))

    print(result)

๐Ÿ‘‰ BFS ๋ฌธ์ œ๋กœ, ๋ชจ๋“  ์ต์€ ํ† ๋งˆํ† ๋“ค์„ ์‹œ์ž‘์ ์œผ๋กœ ๋™์‹œ์— ํƒ์ƒ‰์„ ์ง„ํ–‰ํ•ด์ฃผ๋Š”๊ฒŒ ํฌ์ธํŠธ!

  • ์ฃผ์–ด์ง„ ์ฐฝ๊ณ ์˜ ๋ชจ๋“  ์ž๋ฆฌ๋ฅผ ๋Œ๋ฉฐ 1์ด ์žˆ๋Š” ์ž๋ฆฌ๋Š” queue์— ๋„ฃ์–ด์ฃผ์—ˆ๊ณ ,
    ์ต์€ ํ† ๋งˆํ† ๋“ค์˜ ์ž๋ฆฌ๊ฐ€ ์ €์žฅ๋œ queue๋ฅผ ๊ฐ€์ง€๊ณ  bfs ํ•จ์ˆ˜๋ฅผ ๋Œ๋ ธ๋‹ค.
  • bfs ํ•จ์ˆ˜๋กœ๋Š” queue์— ์ €์žฅ๋œ ํ† ๋งˆํ† ๋“ค์˜ ์ƒํ•˜์ขŒ์šฐ๋ฅผ ํƒ์ƒ‰ํ•˜๊ณ ,
    0์„ ๋ฐœ๊ฒฌํ•˜๋ฉด ํ•ด๋‹น ํ† ๋งˆํ† ๋ฅผ 1๋กœ ๋ฐ”๊พธ์–ด์ฃผ์—ˆ๋‹ค. ๊ทธ๋ฆฌ๊ณ  ํ•œ ๋ฒˆ ํ† ๋งˆํ† ๋ฅผ ์ตํž ๋•Œ๋งˆ๋‹ค
    count์„ ์ฆ๊ฐ€์‹œ์ผœ์ฃผ์–ด์„œ countCheck ๋ฆฌ์ŠคํŠธ์— ๋ˆ„์ ํ•˜์—ฌ ๊ธฐ๋กํ–ˆ๋‹ค.
    ๊ทธ๋ฆฌ๊ณ  ์ด countCheck์˜ ์ตœ๋Œ“๊ฐ’์„ ๊ตฌํ•˜์—ฌ ๊ฒฐ๊ณผ๋กœ ์ถœ๋ ฅํ•˜๊ฒŒ ํ–ˆ๋‹ค.

(์ €๋ฒˆ์— swift๋กœ ํ’€์—ˆ๋˜ ํ’€์ด๐Ÿ‘‡์™€ ์œ ์‚ฌํ•œ ๊ฒƒ ๊ฐ™์•„์„œ ์ž์„ธํ•œ ์„ค๋ช…์€ ์ƒ๋žตํ•˜๊ฒ ๋‹ค.

https://seolhee2750.tistory.com/126)

 

 

๐Ÿ’ก ํ”ผ๋“œ๋ฐฑ
  • ์ „ํ˜•์ ์ธ bfs ๋ฌธ์ œ๋ผ ์‰ฝ๊ฒŒ ํ’€ ์ˆ˜ ์žˆ์—ˆ๋‹ค.

๋Œ“๊ธ€