深度优先查找之迷宫问题

 1 maze = [
 2     [1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
 3     [1, 0, 0, 1, 0, 0, 0, 1, 0, 1],
 4     [1, 0, 0, 1, 0, 0, 0, 1, 0, 1],
 5     [1, 0, 0, 0, 0, 1, 1, 0, 0, 1],
 6     [1, 0, 1, 1, 1, 0, 0, 0, 0, 1],
 7     [1, 0, 0, 0, 1, 0, 0, 0, 0, 1],
 8     [1, 0, 1, 0, 0, 0, 1, 0, 0, 1],
 9     [1, 0, 1, 1, 1, 0, 1, 1, 0, 1],
10     [1, 1, 0, 0, 0, 0, 0, 0, 0, 1],
11     [1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
12 ]
13 dirs = [
14     lambda x, y: (x+1, y),
15     lambda x, y: (x, y+1),
16     lambda x, y: (x-1, y),
17     lambda x, y: (x, y-1),
18 ]
19 
20 
21 def maze_path(start, end):
22     stack = []
23     stack.append(start)
24     while len(stack) != 0:
25         cur_node = stack[-1]
26         if cur_node == end:
27             print('找到迷宫出路:')
28             print(stack)
29             return True
30         for dir in dirs:
31             next_node = dir(cur_node[0], cur_node[1])
32             if maze[next_node[0]][next_node[1]] == 0:
33                 stack.append(next_node)
34                 maze[next_node[0]][next_node[1]] = 2
35                 break
36         else:
37             stack.pop()
38     else:
39         print('没找到')
40         return False
41 
42 
43 if __name__ == '__main__':
44     maze_path((1, 1), (2, 8))

 

上一篇:寻找栈的最小值


下一篇:20_有效的括号