ํ‹ฐ์Šคํ† ๋ฆฌ ๋ทฐ

728x90
๋ฐ˜์‘ํ˜•

๋ฌธ์ œ

 

16236๋ฒˆ: ์•„๊ธฐ ์ƒ์–ด

N×N ํฌ๊ธฐ์˜ ๊ณต๊ฐ„์— ๋ฌผ๊ณ ๊ธฐ M๋งˆ๋ฆฌ์™€ ์•„๊ธฐ ์ƒ์–ด 1๋งˆ๋ฆฌ๊ฐ€ ์žˆ๋‹ค. ๊ณต๊ฐ„์€ 1×1 ํฌ๊ธฐ์˜ ์ •์‚ฌ๊ฐํ˜• ์นธ์œผ๋กœ ๋‚˜๋ˆ„์–ด์ ธ ์žˆ๋‹ค. ํ•œ ์นธ์—๋Š” ๋ฌผ๊ณ ๊ธฐ๊ฐ€ ์ตœ๋Œ€ 1๋งˆ๋ฆฌ ์กด์žฌํ•œ๋‹ค. ์•„๊ธฐ ์ƒ์–ด์™€ ๋ฌผ๊ณ ๊ธฐ๋Š” ๋ชจ๋‘ ํฌ๊ธฐ๋ฅผ ๊ฐ€๏ฟฝ๏ฟฝ

www.acmicpc.net

 

๋ฌธ์ œ ํ’€์ด

 ์•„๊ธฐ ์ƒ์–ด๊ฐ€ NxN ํฌ๊ธฐ์˜ ๊ณต๊ฐ„์— ๋ฌผ๊ณ ๊ธฐ๋ฅผ ๋จน์œผ๋ฉด์„œ ์ด๋™ ํ• ๋•Œ, ์ตœ๋‹จ ์‹œ๊ฐ„์„ ๋ฐ˜ํ™˜ํ•˜์—ฌ์•ผ ํ•œ๋‹ค. ๋ฌธ์ œ์—์„œ๋Š” ์•„๊ธฐ ์ƒ์–ด๊ฐ€ ์›€์ง์ด๊ธฐ ์œ„ํ•œ ์กฐ๊ฑด๋“ค์ด ์กด์žฌํ•œ๋‹ค.

 

  • ์•„๊ธฐ ์ƒ์–ด๋Š” ์ž์‹ ๋ณด๋‹ค ํฌ๊ฑฐ๋‚˜ ๊ฐ™์€ ํฌ๊ธฐ์˜ ๋ฌผ๊ณ ๊ธฐ๋Š” ๋จน์„ ์ˆ˜ ์—†๋‹ค.
  • ๊ฐ€์žฅ ๊ฐ€๊นŒ์ด ์žˆ๋Š” ๋ฌผ๊ณ ๊ธฐ ๋ถ€ํ„ฐ ์šฐ์„ ์ ์œผ๋กœ ๋จน์–ด์•ผ ํ•œ๋‹ค.
  • ์—ฌ๋Ÿฌ ๋งˆ๋ฆฌ๋ฅผ ๋จน์„ ์ˆ˜ ์žˆ๋‹ค๋ฉด, ๊ฐ€์žฅ ์™ผ์ชฝ์— ์žˆ๋Š” ๋ฌผ๊ณ ๊ธฐ๋ฅผ ์šฐ์„  ์ˆœ์œ„๋กœ ๋จน์–ด์•ผ ํ•œ๋‹ค.

 

 ๋ฌธ์ œ๋ฅผ ์ฒ˜์Œ์—๋Š” `BFS`์™€ `sort`๋ฅผ ํ†ตํ•ด ํ’€ ์—ˆ์ง€๋งŒ, `heapq`๋ฅผ ํ™œ์šฉํ•  ๊ฒฝ์šฐ ๋”์šฑ ๊น”๋”ํ•˜๊ณ  ์ฝ”๋“œ๊ฐ€ ์ง๊ด€์ ์ด๋‹ค. `heapq`๋ฅผ ์‚ฌ์šฉํ•˜์—ฌ ์šฐ์„  ์ˆœ์œ„๋ฅผ `(์‹œ๊ฐ„, x, y)`๋กœ ํ•˜์—ฌ ํƒ์ƒ‰์„ ์ง„ํ–‰ํ•œ๋‹ค. ์กฐ๊ฑด์— ๋”ฐ๋ผ ๋” ์ด์ƒ ๋จน์„ ์ˆ˜ ์žˆ๋Š” ๋ฌผ๊ณ ๊ธฐ๊ฐ€ ์—†๋Š” ๊ฒฝ์šฐ ์ข…๋ฃŒํ•˜๋ฉด ๋ฌธ์ œ์—์„œ ์›ํ•˜๋Š” ๋‹ต์„ ์ฐพ์„ ์ˆ˜ ์žˆ๋‹ค.

 

์ฝ”๋“œ

from sys import stdin
from heapq import heappush, heappop


def visitable(x, y, size, visited):
    return 0 <= x < n and 0 <= y < n and graph[x][y] <= size and not visited[x][y]


def bfs(time, shark):
    size, eat, answer = 2, 0, 0

    heap = []
    heappush(heap, (time, shark[X], shark[Y]))
    visited = [[False] * n for _ in range(n)]

    while heap:
        time, x, y = heappop(heap)

        # ๋จน์„ ์ˆ˜ ์žˆ๋Š” ๋ฌผ๊ณ ๊ธฐ๋ผ๋ฉด
        if 0 < graph[x][y] < size:
            eat += 1
            graph[x][y] = 0
            # ํฌ๊ธฐ๊ฐ€ 2๋ผ๋ฉด 2๋งˆ๋ฆฌ๋ฅผ ๋จน์–ด์•ผ ํ•จ.
            if eat == size:
                size += 1
                eat = 0

            answer += time
            time = 0

            # heap, ๋ฐฉ๋ฌธ ์—ฌ๋ถ€ ์ดˆ๊ธฐํ™”
            heap = []
            visited = [[False] * n for _ in range(n)]

        for dx, dy in dirs:
            next_x, next_y = x + dx, y + dy

            if visitable(next_x, next_y, size, visited):
                visited[next_x][next_y] = True
                heappush(heap, (time + 1, next_x, next_y))

    return answer


if __name__ == '__main__':
    X, Y = 0, 1
    n = int(stdin.readline())
    graph = [list(map(int, stdin.readline().split())) for _ in range(n)]
    dirs = ((0, 1), (1, 0), (0, -1), (-1, 0))

    for i in range(n):
        for j in range(n):
            if graph[i][j] == 9:
                graph[i][j] = 0
                print(bfs(0, [i, j]))
                break

 

728x90
๋ฐ˜์‘ํ˜•
๋Œ“๊ธ€
๊ธ€ ๋ณด๊ด€ํ•จ
์ตœ๊ทผ์— ์˜ฌ๋ผ์˜จ ๊ธ€
์ตœ๊ทผ์— ๋‹ฌ๋ฆฐ ๋Œ“๊ธ€