๋ฌธ์
https://www.acmicpc.net/short/status/13219/1
ํ์ด
# ๋ฐฑ์ค 13219๋ฒ ๋ฌธ์ - trains
from heapq import heappush, heappop
import sys
input = sys.stdin.readline
INF = 1e9
dx = [-1, 1, 0, 0]
dy = [0, 0, -1, 1]
n = int(input())
ay, ax, by, bx = map(int, input().split())
ax -= 1
ay -= 1
bx -= 1
by -= 1
graph = [list(map(int, input().split())) for _ in range(n)]
visited = [[INF for _ in range(n)] for _ in range(n)]
q = []
heappush(q, (graph[ax][ay], ax, ay))
visited[ax][ay] = graph[ax][ay]
while q:
cost, x, y = heappop(q)
if graph[x][y] == -1:
break
if cost > visited[x][y]:
continue
for i in range(4):
nx = x + dx[i]
ny = y + dy[i]
if 0 <= nx < n and 0 <= ny < n:
if graph[nx][ny] != -1:
next_cost = cost + graph[nx][ny]
if visited[nx][ny] > next_cost:
visited[nx][ny] = next_cost
heappush(q, (next_cost, nx, ny))
if visited[bx][by] == INF:
print(-1)
else:
print(visited[bx][by])
๋ค์ต์คํธ๋ผ์ BFS๋ฅผ ์ด์ฉํ ๋ฌธ์
'๐๏ธ Algorithm > ๐ฉ ๋ฐฑ์ค' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
๐ฉ [๋ฐฑ์ค] [Python] [Silver3] 2346๋ฒ_ํ์ ํฐ๋จ๋ฆฌ๊ธฐ (0) | 2023.05.29 |
---|---|
๐ฉ [๋ฐฑ์ค] [Python] [Gold4] 1339๋ฒ_๋จ์ด ์ํ (0) | 2023.05.15 |
๐ฉ [๋ฐฑ์ค] [Python] [Gold2] 12015๋ฒ_๊ฐ์ฅ ๊ธด ์ฆ๊ฐํ๋ ๋ถ๋ถ ์์ด 2 (0) | 2023.05.12 |
๐ฉ [๋ฐฑ์ค] [Python] [Gold4] 1043๋ฒ_๊ฑฐ์ง๋ง (0) | 2023.05.12 |
๐ฉ [๋ฐฑ์ค] [Python] [Gold5] 13023๋ฒ_ABCDE (0) | 2023.05.11 |