๐Ÿ—๏ธ Algorithm/๐ŸŸฉ ๋ฐฑ์ค€

๐ŸŸฉ [๋ฐฑ์ค€] [Python] [Gold3] 16236๋ฒˆ_์•„๊ธฐ ์ƒ์–ด

Dbswnstjd 2023. 2. 21. 21:47

๋ฌธ์ œ

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

 

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

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

www.acmicpc.net

ํ’€์ด

# ๋ฐฑ์ค€ 16236๋ฒˆ ๋ฌธ์ œ - ์•„๊ธฐ ์ƒ์–ด 
from collections import deque
dx, dy = [0,0,-1,1],[1,-1,0,0]
n = int(input())
graph = [list(map(int, input().split())) for _ in range(n)]
x, y, shark_size = 0,0,2

for i in range(n):
    for j in range(n):
        if graph[i][j] == 9:
            x, y = i, j

def bfs(x,y,shark_size):
    visited = [[0]*n for _ in range(n)]
    distance = [[0]*n for _ in range(n)]
    q = deque()
    q.append((x, y))
    visited[x][y] = 1
    temp = []

    while q:
        x, y = q.popleft()
        for i in range(4):
            nx = x + dx[i]
            ny = y + dy[i]
            if 0 <= nx < n and 0 <= ny < n and not visited[nx][ny]:
                if graph[nx][ny] <= shark_size:
                    q.append((nx, ny))
                    visited[nx][ny] = 1
                    distance[nx][ny] = distance[x][y] + 1
                    if 0 < graph[nx][ny] < shark_size:
                        temp.append((nx, ny, distance[nx][ny]))

    return sorted(temp, key=lambda x: (-x[2], -x[0], -x[1]))

cnt = 0
result = 0
while True:
    shark = bfs(x, y, shark_size)
    if len(shark) == 0:
        break

    nx, ny, dist = shark.pop()
    
    result += dist
    graph[x][y], graph[nx][ny] = 0,0
    x, y = nx, ny
    cnt += 1

    if shark_size == cnt:
        shark_size += 1
        cnt = 0
print(result)

๊ฐ€์žฅ ๊ฐ€๊นŒ์šด ๋ฌผ๊ณ ๊ธฐ๋ฅผ ๋งŒ๋‚˜๋Š” ์กฐ๊ฑด์—์„œ ์กฐ๊ธˆ ํ—ท๊ฐˆ๋ ธ๋‹ค. 

ํ•˜์ง€๋งŒ BFS์˜ ํŠน์ง•์„ ๋ณด๋ฉด ๊ฐ€์žฅ ๋จผ์ € ๋งŒ๋‚˜๋Š” ๋ฌผ๊ณ ๊ธฐ๊ฐ€ ๊ฐ€์žฅ ๊ฐ€๊นŒ์šด ๋ฌผ๊ณ ๊ธฐ๋ผ๊ณ  ํ•  ์ˆ˜ ์žˆ๋‹ค.

๋”ฐ๋ผ์„œ BFS๋ฅผ ์‚ฌ์šฉํ•˜๋ฉด ํ•ด๊ฒฐ์ด ๊ฐ€๋Šฅํ•œ ๋ฌธ์ œ์˜€๋‹ค.