~๋ชฉ์ฐจ~
๋ฌธ์
https://www.acmicpc.net/problem/4485
๋ฌธ์ ํด๊ฒฐ ํฌ์ธํธ
- ๋ค์ต์คํธ๋ผ๋ฅผ ์ด์ฉํ์ฌ ๊ฐ ์์น๋ณ (0, 0)์์ ์ต์ ๋น์ฉ์ ๊ณ์ฐ
- dr, dc : ๊ฐ ์์น์์ ์๋, ์, ์ค๋ฅธ์ชฝ, ์ผ์ชฝ ์์น๋ฅผ ๋ฐฉ๋ฌธ ํ๊ธฐ ์ํ ๋ฐฉํฅํค
- graph : ๊ฐ ์์น ๋ฐฉ๋ฌธ์ ์ํด ํ์ํ ๋น์ฉ
- distance : ๊ฐ ์์น์์ (0, 0)๊น์ง ๊ฐ๊ธฐ์ํ ์ต์ ๋น์ฉ, ์ด๊ธฐ๋ ๋ฌดํ์
์์ฑ ์ฝ๋
import heapq
INF = int(1e9)
dr = [1, -1, 0, 0] # down, up, right, left
dc = [0, 0, 1, -1]
test = 1
while True:
n = int(input())
if n == 0:
break
distance = [[INF]*(n+1) for _ in range(n+1)]
graph = [[] for _ in range(n)]
for i in range(n):
graph[i] = list(map(int, input().split()))
def dijkstra(y, x):
q = []
distance[y][x] = graph[0][0]
heapq.heappush(q, (graph[0][0], y, x))
while q:
dist, row, col = heapq.heappop(q)
if distance[row][col] < dist:
continue
for d in range(4):
r = row + dr[d]
c = col + dc[d]
if -1 < r < n and -1 < c < n and distance[r][c] > graph[r][c] + dist:
distance[r][c] = dist + graph[r][c]
heapq.heappush(q, (distance[r][c], r, c))
dijkstra(0, 0)
print("Problem {}: {}".format(test, distance[n-1][n-1]))
test += 1
๋์์ด ๋์ จ๋ค๋ฉด ์ข์์ ๋๋ฌ์ฃผ์ธ์๐
๊ถ๊ธํ ์ ์ด ์๋ค๋ฉด ๋๊ธ ๋ฌ์์ฃผ์ธ์!
'๐๋ฌธ์ ํ์ด > ๐งฉBaekjoon' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[Python] ๋ฐฑ์ค 18405 ๊ฒฝ์์ ์ ์ผ | BFS (0) | 2023.05.20 |
---|---|
[Python] ๋ฐฑ์ค 14502 ์ฐ๊ตฌ์ | BFS (0) | 2023.05.20 |
[Python] ๋ฐฑ์ค 1504 ํน์ ํ ์ต๋จ ๊ฒฝ๋ก | ๋ค์ต์คํธ๋ผ (0) | 2023.05.17 |
[Python] ๋ฐฑ์ค 13549 ์จ๋ฐ๊ผญ์ง 3 | ๋ค์ต์คํธ๋ผ (0) | 2023.05.17 |
[Python] ๋ฐฑ์ค 1916 ์ต์๋น์ฉ ๊ตฌํ๊ธฐ | ๋ค์ต์คํธ๋ผ | ์๊ฐ์ด๊ณผ (0) | 2023.05.17 |