-
Notifications
You must be signed in to change notification settings - Fork 0
/
12-part1.py
96 lines (83 loc) · 2.7 KB
/
12-part1.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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
#!/usr/bin/python3
import fileinput
import sys
def djkstra_build_initial_datastructure():
global lines
data = {}
start_vertex = find_vertex_start()
for y in range(0,len(lines)):
for x in range(0,len(lines[0])):
data[(y,x)] = {
'shortest_distance': 99999,
'previous_vertex': None,
'visited': False
}
if (y,x) == start_vertex:
data[(y,x)]['shortest_distance'] = 0
return data
def djkstra_visit(data):
tovisit = None
shortest_distance = 99999
for i in data:
if data[i]['visited'] == True:
continue
if data[i]['shortest_distance'] < shortest_distance:
tovisit = i
shortest_distance = data[i]['shortest_distance']
if tovisit == None:
return None
neighbors = get_vertex_neighbors(tovisit)
for i in neighbors:
current_best_distance = data[i]['shortest_distance']
new_best_distance = data[tovisit]['shortest_distance'] + 1
if new_best_distance < current_best_distance:
data[i]['shortest_distance'] = new_best_distance
data[i]['previous_vertex'] = tovisit
data[tovisit]['visited'] = True
return True
def get_vertex_neighbors(vertex):
global max_x
global max_y
neighbors = []
candidate_neighbors = (
(vertex[0] - 1,vertex[1]), # UP
(vertex[0] + 1,vertex[1]), # DOWN
(vertex[0],vertex[1] - 1), # LEFT
(vertex[0],vertex[1] + 1) # RIGHT
)
for i in candidate_neighbors:
if (0 <= i[0] <= max_y) and (0 <= i[1] <= max_x):
if (get_vertex_elevation(i) - get_vertex_elevation(vertex)) < 2:
neighbors.append(i)
return neighbors
def get_vertex_elevation(vertex):
global lines
if vertex == find_vertex_start():
return ord('a')
if vertex == find_vertex_end():
return ord('z')
return ord(lines[vertex[0]][vertex[1]])
def find_vertex_from_char(mychar):
global lines
for y in range(0,len(lines)):
for x in range(0,len(lines[0])):
if lines[y][x] == mychar:
return (y,x)
def find_vertex_start():
return find_vertex_from_char('S')
def find_vertex_end():
return find_vertex_from_char('E')
# Main
lines = []
for line in fileinput.input():
line = line.rstrip('\n')
lines.append(line)
max_y = len(lines) - 1
max_x = len(lines[0]) -1
print("please wait, calculations can take a couple of minutes...", file=sys.stderr)
data = djkstra_build_initial_datastructure()
while True:
result = djkstra_visit(data)
if result == None:
break
print(data[find_vertex_end()]['shortest_distance'])