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 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103
   | ''' Edit by lx Blog: blog.lxscloud.top ''' import copy
 
  maze = [     [1,1,1,1,1,1,1,1,1,1],     [1,0,0,1,0,0,0,1,0,1],     [1,0,0,1,0,0,0,1,0,1],     [1,0,0,0,0,1,1,0,0,1],     [1,0,1,1,1,0,0,0,0,1],     [1,0,0,0,1,0,0,0,0,1],     [1,0,1,0,0,0,1,0,0,1],     [1,0,1,1,1,0,1,1,0,1],     [1,1,0,0,0,0,0,0,0,1],     [1,1,1,1,1,1,1,1,1,1] ]
  maze_cp1 = [] maze_cp1 = copy.deepcopy(maze)
  ''' 功能:构造函数,可以根据需要将输入坐标处理为上,右,下,左 ''' dirs = [     lambda x,y:(x-1,y),       lambda x,y:(x,y+1),       lambda x,y:(x+1,y),       lambda x,y:(x,y-1),   ] id_d = ["向上走", "往右走", "向下走", "往左走"]
  ''' 功能:走迷宫 ''' def solve_maze(x1, y1, x2, y2, maze_cp):     global stack_cp     direction = []     stack = []     stack.append((x1,y1))     direction.append("在原点")     maze_cp[x1][y1] = 2     while len(stack) > 0:            cur_node = stack[-1]         if cur_node == (x2,y2):              stack_cp = copy.deepcopy(stack)             for ii, p in enumerate(stack):                 print(p, direction[ii])             return True         for index_d, dir in enumerate(dirs):             next_node = dir(*cur_node)             if maze_cp[next_node[0]][next_node[1]] == 0:                    stack.append(next_node)                 direction.append(id_d[index_d])                 maze_cp[next_node[0]][next_node[1]] = 2                   break         else:              stack.pop()             direction.pop()     else:         print("无路可走")         return False ''' 功能:输出迷宫图 ''' def print_maze(maze_ip):     for ind in range(len(maze_ip)):         for i in maze_ip[ind]:             if i == 1:               print("*", end=" ")             elif i == 0:               print("-", end=" ")         print() ''' 功能:输出路线图 '''     def print_maze_done(maze_ip):     print("原迷宫:")     print_maze(maze_ip)     print("路线:")     for ind in range(len(maze_ip)):         for ind1, i in enumerate(maze_ip[ind]):             if i == 1:               print("*", end=" ")             elif i == 0:               bool_ = False               for data_ in stack_cp:                 if data_ == (ind, ind1):                   bool_ = True                   break               if bool_:                 print("@", end=" ")               else:                 print("-", end=" ")         print()      print("走迷宫吼") print_maze(maze) solve_maze(1,1,8,8,maze)  print_maze_done(maze_cp1)
 
   |