一道python走迷宫算法题

时间:2022-09-23 12:24:05

前几天逛博客时看到了这样一道问题,感觉比较有趣,就自己思考了下方案顺便用python实现了一下。题目如下:

用一个二维数组表示一个简单的迷宫,用0表示通路,用1表示阻断,老鼠在每个点上可以移动相邻的东南西北四个点,设计一个算法,模拟老鼠走迷宫,找到从入口到出口的一条路径。

如图所示:

一道python走迷宫算法题

先说下我的思路吧:

1、首先用一个列表source存储迷宫图,一个列表route_stack存储路线图,一个列表route_history存储走过的点,起点(0,0),终点(4,4)。

2、老鼠在每个点都有上下左右四种方案可选,需要定义这些方案的执行方法。

3、最后做一个循环,如果当前点不是(4,4)的话就依次执行上下左右四种方法,但是有些限制,比如尝试走过的点不会再尝试走,(0,x)点无法再执行向上的方法等等。

贴一下代码:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
# _*_ coding:utf-8 _*_ 
route_stack = [[0,0]]
route_history = [[0,0]]
source=[[0,0,1,0,1],[1,0,0,0,1],[0,0,1,1,0],[0,1,0,0,0],[0,0,0,1,0]]
def up(location):
  #横坐标为0,无法再向上走
  if location[1] == 0:
    return False
  else:
    new_location = [location[0],location[1]-1]
    #已经尝试过的点不会尝试第二次
    if new_location in route_history:
      return False
    #碰到墙不走
    elif source[new_location[0]][new_location[1]] == 1:
      return False
    else:
      route_stack.append(new_location)
      route_history.append(new_location)
      return True
 
def down(location):
  if location[1] == 4:
    return False
  else:
    new_location = [location[0],location[1]+1]
    if new_location in route_history:
      return False
    elif source[new_location[0]][new_location[1]] == 1:
      return False
    else:
      route_stack.append(new_location)
      route_history.append(new_location)
      return True
 
def left(location):
  if location[0] == 0:
    return False
  else:
    new_location = [location[0]-1,location[1]]
    if new_location in route_history:
      return False
    elif source[new_location[0]][new_location[1]] == 1:
      return False
    else:
      route_stack.append(new_location)
      route_history.append(new_location)
      return True
 
def right(location):
  if location[0] == 4:
    return False
  else:
    new_location = [location[0]+1,location[1]]
    if new_location in route_history:
      return False
    elif source[new_location[0]][new_location[1]] == 1:
      return False
    else:
      route_stack.append(new_location)
      route_history.append(new_location)
      return True
lo = [0,0]
while route_stack[-1] != [4,4]:
  if up(lo):
    lo = route_stack[-1]
    continue
  if down(lo):
    lo = route_stack[-1]
    continue
  if left(lo):
    lo = route_stack[-1]
    continue
  if right(lo):
    lo = route_stack[-1]
    continue
  route_stack.pop()
  lo = route_stack[-1]
print route_stack

执行结果如下:

一道python走迷宫算法题

题目出处有另一种解题思路,但是我觉得有点烦,自己的这个比较好理解点,实现起来也比较方便。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持服务器之家。

原文链接:http://blog.csdn.net/sinly100/article/details/72832805