Python(1923)
バックトラック検索
確かに最短でも最も効率的でもありませんが、いくつかのメモがあります。
import random
l = 10
map = [
[(lambda i: 0 if i < 7 else 1 if i < 10 else 2)(random.randint(1, 10))
for i in range(0, l)]
for i in range(0, l)
]
map[0][0] = map[l-1][l-1] = 0
print "\n".join([" ".join([str(i) for i in x]) for x in map])
paths = {}
def step(past_path, x, y):
shortest = float("inf")
shortest_path = []
current_path = past_path + [(x, y)]
pos = map[x][y]
if (x, y) != (0, 0):
past_pos = map[past_path[-1][0]][past_path[-1][1]]
if (((x, y) in paths or str(current_path) in paths)
and (pos != 2 or past_pos == 2)):
return paths[(x, y)]
elif x == l-1 and y == l-1:
return ([(x, y)], 1)
if pos == 1:
return (shortest_path, shortest)
if pos == 2 and past_pos != 2:
for i2 in range(0, l):
for j2 in range(0, l):
pos2 = map[i2][j2]
if pos2 == 2 and (i2, j2) not in current_path:
path, dist = step(current_path, i2, j2)
if dist < shortest and (x, y) not in path:
shortest = dist
shortest_path = path
else:
for i in range(x - 1, x + 2):
for j in range(y - 1, y + 2):
if i in range(0, l) and j in range(0, l):
pos = map[i][j]
if pos in [0, 2] and (i, j) not in current_path:
path, dist = step(current_path, i, j)
if dist < shortest and (x, y) not in path:
shortest = dist
shortest_path = path
dist = 1 + shortest
path = [(x, y)] + shortest_path
if dist != float("inf"):
paths[(x, y)] = (path, dist)
else:
paths[str(current_path)] = (path, dist)
return (path, dist)
p, d = step([], 0, 0)
if d != float("inf"):
print p, d