Add solution for day 12
This commit is contained in:
1 parent
a1b8159007
commit
6aec568b24
3 files changed
+171
No files matched your search
Executable
+68
@@ -0,0 +1,68 @@
|
||||
#!/usr/bin/env python3
|
||||
|
||||
import sys
|
||||
|
||||
|
||||
def parse_graph(p):
|
||||
graph = {}
|
||||
start = None
|
||||
end = None
|
||||
a = []
|
||||
for i in range(len(p)): # y dir
|
||||
for j in range(len(p[i])): # x dir
|
||||
if p[i][j] == 'S':
|
||||
start = (j,i)
|
||||
p[i][j] = 'a'
|
||||
elif p[i][j] == 'E':
|
||||
end = (j,i)
|
||||
p[i][j] = 'z'
|
||||
if p[i][j] == 'a': a.append((j,i))
|
||||
graph[(j,i)] = []
|
||||
for (x,y) in set([(max(0,j-1),i),(min(len(p[i])-1,j+1),i),(j,max(0,i-1)),(j,min(len(p)-1,i+1))]):
|
||||
if (ord(p[y][x])-1)<=ord(p[i][j]): graph[(j,i)].append((x,y))
|
||||
return graph, start, end, a
|
||||
|
||||
|
||||
def bfs(g,start,end):
|
||||
Q = [start]
|
||||
expl = [start]
|
||||
parent = {}
|
||||
parent[start] = None
|
||||
while len(Q) > 0:
|
||||
v = Q.pop(0)
|
||||
if v == end: return parent
|
||||
for w in g[v]:
|
||||
if w not in expl:
|
||||
expl.append(w)
|
||||
parent[w] = v
|
||||
Q.append(w)
|
||||
|
||||
def path(parent, end):
|
||||
length = 0
|
||||
v = end
|
||||
while parent[v] != None:
|
||||
length = length + 1
|
||||
v = parent[v]
|
||||
return length
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
points = [list(line.strip('\n')) for line in open(sys.argv[1])]
|
||||
|
||||
g, s, e, az = parse_graph(points)
|
||||
par = bfs(g, s, e)
|
||||
shortest = path(par,e)
|
||||
|
||||
# challenge 1
|
||||
res1 = str(shortest)
|
||||
print("challenge 1:" + "\n" + res1 + "\n")
|
||||
|
||||
# challenge 2
|
||||
for a in az:
|
||||
par = bfs(g, a, e)
|
||||
if par != None: s = path(par,e)
|
||||
if s < shortest: shortest = s
|
||||
|
||||
res2 = str(shortest)
|
||||
print("challenge 2:" + "\n" + res2 + "\n")
|
||||
|
||||
Reference in new issue
Block a user