-
Notifications
You must be signed in to change notification settings - Fork 0
/
star2.py
64 lines (51 loc) · 1.55 KB
/
star2.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
63
64
import numpy as np
import heapq
sampleData = \
"""1163751742
1381373672
2136511328
3694931569
7463417111
1319128137
1359912421
3125421639
1293138521
2311944581"""
data = open('data.txt', 'r', encoding="utf-8").read()
# data = sampleData
def dijkstra(graph: dict, start: str):
dist, prev = {}, {}
result = []
for vertice in graph:
dist[vertice] = float('inf')
prev[vertice] = None
dist[start] = 0
Q = [(0, start)]
while Q:
_, u = heapq.heappop(Q)
result.append(u)
for neighbor in graph[u]:
alt = dist[u] + graph[u][neighbor]
if alt < dist[neighbor]:
dist[neighbor] = alt
prev[neighbor] = u
heapq.heappush(Q, (dist[neighbor], neighbor))
return result, dist, prev
df = np.array([[int(x) for x in line] for line in data.splitlines()])
row = np.hstack([(df + i - 1) % 9 + 1 for i in range(5)])
matrix = np.vstack([(row + i - 1) % 9 + 1 for i in range(5)])
# for i in range(5):
graph = dict()
for x in range(len(matrix)):
for y in range(len(matrix[0])):
graph[f'{x},{y}'] = dict()
if y > 0:
graph[f'{x},{y}'][f'{x},{y-1}'] = matrix[y-1][x]
if y < len(matrix) - 1:
graph[f'{x},{y}'][f'{x},{y+1}'] = matrix[y+1][x]
if x > 0:
graph[f'{x},{y}'][f'{x-1},{y}'] = matrix[y][x-1]
if x < len(matrix[0]) - 1:
graph[f'{x},{y}'][f'{x+1},{y}'] = matrix[y][x+1]
s, distance, previous = dijkstra(graph, '0,0')
print(distance[f'{len(matrix)-1},{len(matrix)-1}'])