You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
68 lines
1.6 KiB
68 lines
1.6 KiB
#!/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")
|
|
|
|
|