-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path16236.py
62 lines (54 loc) ยท 1.83 KB
/
16236.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
import sys
from collections import deque
input = sys.stdin.readline
n = int(input().rstrip())
graph = [list(map(int, input().rstrip().split())) for _ in range(n)]
dx = [-1, 0, 0, 1]
dy = [0, -1, 1, 0]
time = 0
baby = [2, 0]
baby_loc = []
for i in range(n):
for j in range(n):
if graph[i][j] == 9:
baby_loc = [i, j]
while True:
visited = [[False for _ in range(n)] for _ in range(n)]
q = deque([])
q.append([baby_loc[0], baby_loc[1], 0])
finish = False
candidates = []
while q:
x, y, dist = q.popleft()
for x_, y_ in zip(dx, dy):
nx = x + x_
ny = y + y_
if 0 <= nx < n and 0 <= ny < n:
if not finish:
if graph[nx][ny] == 0 or graph[nx][ny] == baby[0]:
if visited[nx][ny] == False:
visited[nx][ny] = True
q.append([nx, ny, dist+1])
elif graph[nx][ny] < baby[0] and visited[nx][ny] == False:
visited[nx][ny] = True
finish = True
distance = dist + 1
candidates.append([distance, nx, ny])
else:
if 0 < graph[nx][ny] < baby[0] and visited[nx][ny] == False:
visited[nx][ny] = True
distance = dist + 1
candidates.append([distance, nx, ny])
if len(candidates) == 0:
break
candidates = sorted(candidates, key = lambda x : (x[0], x[1], x[2]))
distance, nx, ny = candidates[0][0], candidates[0][1], candidates[0][2]
time += distance
graph[nx][ny] = 9
graph[baby_loc[0]][baby_loc[1]] = 0
baby_loc = [nx, ny]
baby[1] += 1
if baby[0] == baby[1]:
baby[0] += 1
baby[1] = 0
print(time)