迷宫问题求解
import numpy as np
map = [
[0,1,0,0,0,0],
[0,1,1,1,0,0],
[0,1,0,1,1,0],
[1,1,0,0,1,0],
[0,0,0,0,0,0],
[0,0,0,0,0,0]
]
start = [0,0]
end = [5,5]
print(map)
[[0, 1, 0, 0, 0, 0], [0, 1, 1, 1, 0, 0], [0, 1, 0, 1, 1, 0], [1, 1, 0, 0, 1, 0], [0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0]]
dist = [[0,1],[1,0],[0,-1],[-1,0]]
def mark(map,pos):
map[pos[0]][pos[1]] = 2
def ispossible(map, pos):
return map[pos[0]][pos[1]] == 0
1.递归求解
map = [
[0,1,0,0,0,0],
[0,1,1,1,0,0],
[0,0,0,1,1,0],
[1,1,0,0,1,0],
[0,0,0,0,0,0],
[0,0,0,0,0,0]
]
count = 0
def find_recurrence(map,pos):
global count
count += 1
mark(map,pos)
if pos == end:
return True
else:
for i in range(0,4):
next = [pos[0]+dist[i][0],pos[1]+dist[i][1]]
if next[0] < 0 or next[1] < 0 or next[0] > 5 or next[1] > 5:
continue
if ispossible(map,next):
if find_recurrence(map,next):
return True
return False
if find_recurrence(map,start):
print('找到,共用',count,'步')
print(np.array(map).reshape(6,6))
else:
print('没有找到')
找到,共用 11 步
[[2 1 0 0 0 0]
[2 1 1 1 0 0]
[2 2 2 1 1 0]
[1 1 2 2 1 0]
[0 0 0 2 2 2]
[0 0 0 0 0 2]]
2.栈和回溯法
map = [
[0,1,0,0,0,0],
[0,1,1,1,0,0],
[0,0,0,1,1,0],
[1,1,0,0,1,0],
[0,0,0,0,0,0],
[0,0,0,0,0,0]
]
count = 0
stack = []
def find_recall(map,pos):
global count,stack
stack.append((pos,0))
while len(stack)>0:
pos, next = stack.pop()
print(pos,next)
for i in range(next, 4):
nextp = [pos[0]+dist[i][0],pos[1]+dist[i][1]]
if nextp[0] < 0 or nextp[1] < 0 or nextp[0] > 5 or nextp[1] > 5:
continue
if nextp == end:
return True
if ispossible(map,nextp):
stack.append((pos,i+1))
mark(map, nextp)
stack.append((nextp,0))
break
return False
if find_recall(map,start):
print('路径')
print(stack)
print(np.array(map).reshape(6,6))
else:
print('没有找到')
[0, 0] 0
[1, 0] 0
[2, 0] 0
[2, 1] 0
[2, 2] 0
[3, 2] 0
[3, 3] 0
[4, 3] 0
[4, 4] 0
[4, 5] 0
路径
[([0, 0], 2), ([1, 0], 2), ([2, 0], 1), ([2, 1], 1), ([2, 2], 2), ([3, 2], 1), ([3, 3], 2), ([4, 3], 1), ([4, 4], 1)]
[[0 1 0 0 0 0]
[2 1 1 1 0 0]
[2 2 2 1 1 0]
[1 1 2 2 1 0]
[0 0 0 2 2 2]
[0 0 0 0 0 0]]
3.队列方法 略