https://www.acmicpc.net/problem/19238
import sys
from collections import deque
def solution():
read = sys.stdin.readline
n, m, fuel = map(int, read().split())
board = [0]+[[0]+list(map(int, read().split())) for _ in range(n)]
ty, tx = map(int, read().split())
guests = dict()
for _ in range(m):
sy, sx, ey, ex = map(int, read().split())
guests[(sy, sx)] = {(ey, ex)}
possible = True
while guests:
# 최단 거리 승객 위치 찾기
dist, sy, sx = bfs(ty, tx, n, board, guests)
if dist > fuel:
possible = False
break
fuel -= dist
# 도착지 가기
dist, ey, ex = bfs(sy, sx, n, board, guests[(sy, sx)])
if dist > fuel:
possible = False
break
fuel -= dist
fuel += dist * 2
del guests[(sy, sx)]
ty, tx = ey, ex
if possible:
print(fuel)
else:
print(-1)
def bfs(sy, sx, n, board, dest):
guests = []
dy, dx = [-1,0,0,1], [0, -1, 1, 0]
visited = [[0]*(n+1) for _ in range(n+1)]
visited[sy][sx] = 1
q = deque([[sy, sx, 0]])
while q:
cy, cx, cd = q.popleft()
if (cy, cx) in dest:
guests.append([cd,cy,cx])
for d in range(4):
ny, nx = cy+dy[d], cx+dx[d]
if 1 <= ny <= n and 1 <= nx <= n:
if board[ny][nx] == 0 and not visited[ny][nx]:
visited[ny][nx] = 1
q.append([ny,nx,cd+1])
if guests:
guests.sort()
return guests[0]
return float('inf'), -1, -1
solution()