๋ฌธ์
https://www.acmicpc.net/problem/16236
ํ์ด
# ๋ฐฑ์ค 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๋ฅผ ์ฌ์ฉํ๋ฉด ํด๊ฒฐ์ด ๊ฐ๋ฅํ ๋ฌธ์ ์๋ค.
'๐๏ธ Algorithm > ๐ฉ ๋ฐฑ์ค' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
๐ฉ [๋ฐฑ์ค] [Python] [Gold4] 3190๋ฒ_๋ฑ (0) | 2023.02.23 |
---|---|
๐ฉ [๋ฐฑ์ค] [Python] [Gold4] 2110๋ฒ_๊ณต์ ๊ธฐ ์ค์น (0) | 2023.02.21 |
๐ฉ [๋ฐฑ์ค] [Python] [Gold2] 1300๋ฒ_K๋ฒ์งธ ์ (0) | 2023.02.20 |
๐ฉ [๋ฐฑ์ค] [Python] [Gold4] 10830๋ฒ_ํ๋ ฌ ์ ๊ณฑ (0) | 2023.02.20 |
๐ฉ [๋ฐฑ์ค] [Python] [Silver4] 2960๋ฒ_์๋ผํ ์คํ ๋ค์ค์ ์ฒด (0) | 2023.02.19 |