-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path12-1.py
executable file
·66 lines (52 loc) · 2.03 KB
/
12-1.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
#!/usr/bin/env python
import heapq
import numpy
class Map:
def __init__(self, input):
self.height = len(input)
self.width = len(input[0])
self.map = numpy.zeros((self.height, self.width), dtype=numpy.uint)
for row in range(self.height):
for col in range(self.width):
if input[row][col] == "S":
self.start = [row, col]
self.map[row, col] = 0
elif input[row][col] == "E":
self.end = [row, col]
self.map[row, col] = ord('z') - ord('a')
else:
self.map[row, col] = ord(input[row][col]) - ord('a')
self.lengths = numpy.empty((self.height, self.width), dtype=numpy.uint)
self.lengths.fill(pow(2, 32) - 1)
self.lengths[self.start[0], self.start[1]] = 0
def solve(self):
queue = []
heapq.heappush(queue, (0, (self.start[0], self.start[1])))
while len(queue) > 0:
length, coords = heapq.heappop(queue)
row, col = coords
if length > self.lengths[row, col]:
continue
ns = [
[row + 1, col],
[row - 1, col],
[row, col + 1],
[row, col - 1]
]
neighbours = []
for n in ns:
if n[0] >= 0 and \
n[0] < self.height and \
n[1] >= 0 and \
n[1] < self.width and \
self.map[n[0], n[1]] <= self.map[row, col] + 1:
neighbours.append((n[0], n[1]))
for v in neighbours:
new_length = length + 1
if new_length < self.lengths[v[0], v[1]]:
self.lengths[v[0], v[1]] = new_length
heapq.heappush(queue, (new_length, (v[0], v[1])))
return self.lengths[self.end[0], self.end[1]]
lines = [list(line.strip()) for line in open('12.input').readlines()]
map = Map(lines)
print(map.solve())