Rat in a Maze

本文介绍了一种使用回溯法解决迷宫问题的方法。通过递归地探索可能的路径,该算法能够从迷宫的起点找到到达终点的路径。文章提供了一个C++实现示例。
 

Geeks 面试题: Rat in a Maze 回溯法解迷宫 

标签: Geeks面试题Rat in a Maze回溯法解迷宫
  1632人阅读  评论(3)  收藏  举报
  分类:
 

We have discussed Backtracking and Knight’s tour problem in Set 1. Let us discuss Rat in a Maze as another example problem that can be solved using Backtracking.

A Maze is given as N*N binary matrix of blocks where source block is the upper left most block i.e., maze[0][0] and destination block is lower rightmost block i.e., maze[N-1][N-1]. A rat starts from source and has to reach destination. The rat can move only in two directions: forward and down.
In the maze matrix, 0 means the block is dead end and 1 means the block can be used in the path from source to destination. Note that this is a simple version of the typical Maze problem. For example, a more complex version can be that the rat can move in 4 directions and a more complex version can be with limited number of moves.

Following is an example maze.

 Gray blocks are dead ends (value = 0). 

Following is binary matrix representation of the above maze.

                {1, 0, 0, 0}
                {1, 1, 0, 1}
                {0, 1, 0, 0}
                {1, 1, 1, 1}

Following is maze with highlighted solution path.

Following is the solution matrix (output of program) for the above input matrx.

                {1, 0, 0, 0}
                {1, 1, 0, 0}
                {0, 1, 0, 0}
                {0, 1, 1, 1}
 All enteries in solution path are marked as 1.

Naive Algorithm
The Naive Algorithm is to generate all paths from source to destination and one by one check if the generated path satisfies the constraints.

while there are untried paths
{
   generate the next path
   if this path has all blocks as 1
   {
      print this path;
   }
}

Backtrackng Algorithm

If destination is reached
    print the solution matrix
Else
   a) Mark current cell in solution matrix as 1. 
   b) Move forward in horizontal direction and recursively check if this 
       move leads to a solution. 
   c) If the move chosen in the above step doesn't lead to a solution
       then move down and check if  this move leads to a solution. 
   d) If none of the above solutions work then unmark this cell as 0 
       (BACKTRACK) and return false.


Backtracking 回溯法的三部曲:

1 初始化原始数据,开始点

2 判断下一步是否合法,如果合法就继续递归搜索答案,如果不合法就返回

3 递归直到找到答案,返回真值

这里只需要找到一个解就可以,所以只要找到一个解就可以马上返回。

Leetcode上很喜欢找出所有解的,那么就需要递归所以可能路径了。


说明一下,原题意是规定往下和往右这两个方向探索的,相当于简化了。

这里给出的程序是可以上下左右四个方向探索的,相当于全功能版的解迷宫了,当然,回溯算法是OK的了,类可以继续扩展。

[cpp]  view plain  copy
 print ? 在CODE上查看代码片 派生到我的代码片
  1. class Maze  
  2. {  
  3.     vector<vector<bool> > maze;  
  4.     vector<vector<bool> > solMaze;  
  5.     int row, col;  
  6. public:  
  7.     Maze():maze(6), row(6), col(6), solMaze(6, vector<bool>(6))  
  8.     {  
  9.         bool a[6][6] = {  
  10.             {0,1,0,0,0,0},  
  11.             {0,0,0,1,1,0},  
  12.             {1,1,1,0,0,0},  
  13.             {0,0,0,0,1,1},  
  14.             {1,1,0,1,0,0},  
  15.             {0,0,0,0,0,0}};  
  16.         for (int i = 0; i < 6; i++)  
  17.         {  
  18.             maze[i].assign(a[i], a[i]+6);  
  19.         }  
  20.     }  
  21.     bool isLegal(int x, int y)  
  22.     {  
  23.         return x>=0 && y>=0 && x<col && y<row && !maze[x][y] && !solMaze[x][y];  
  24.     }  
  25.   
  26.     bool solveMaze(int x, int y)  
  27.     {  
  28.         if (x == col-1 && y == row-1)   
  29.         {  
  30.             solMaze[x][y] = 1;  
  31.             return true;  
  32.         }  
  33.   
  34.         if (isLegal(x, y))  
  35.         {  
  36.             solMaze[x][y] = 1;  
  37.   
  38.             if (solveMaze(x, y+1)) return true;  
  39.             if (solveMaze(x+1, y)) return true;  
  40.             if (solveMaze(x-1, y)) return true;  
  41.             if (solveMaze(x, y-1)) return true;  
  42.   
  43.             solMaze[x][y] = 0;  
  44.         }  
  45.         return false;  
  46.     }  
  47.   
  48.     void printSolution()  
  49.     {  
  50.         for (auto x:solMaze)  
  51.         {  
  52.             for (auto y:x)  
  53.                 cout<<y<<" ";  
  54.             cout<<endl;  
  55.         }  
  56.     }  
  57. };  
  58.   
  59. int main()  
  60. {  
  61.     cout<<"C++ Class Solution\n";  
  62.     Maze ma;  
  63.     ma.solveMaze(0,0);  
  64.     ma.printSolution();  
  65.   
  66.     system("pause");  
  67.     return 0;  
  68. }  



import numpy as np import random import time from collections import deque import os # 迷宫生成类 class MazeGenerator: @staticmethod def generate_maze(width, height): """使用DFS算法生成迷宫""" # 初始化迷宫(1表示墙,0表示路径) maze = np.ones((height, width), dtype=int) # 起点和终点 start = (1, 1) end = (height - 2, width - 2) # DFS生成迷宫 stack = [start] maze[start] = 0 while stack: current = stack[-1] x, y = current # 获取未访问的邻居(距离为2的单元格) neighbors = [] for dx, dy in [(0, 2), (2, 0), (0, -2), (-2, 0)]: nx, ny = x + dx, y + dy if 0 < nx < height - 1 and 0 < ny < width - 1 and maze[nx, ny] == 1: # 修正:将墙位置单独存储 wall_pos = (x + dx//2, y + dy//2) neighbors.append((nx, ny, wall_pos)) # 现在是三元组 if neighbors: # 修正:正确解包三元组 next_x, next_y, wall_pos = random.choice(neighbors) next_cell = (next_x, next_y) maze[next_cell] = 0 maze[wall_pos] = 0 stack.append(next_cell) else: stack.pop() # 设置起点和终点 maze[start] = 2 # 起点标记为2 maze[end] = 3 # 终点标记为3 return maze # 迷宫游戏类 class MazeGame: def __init__(self): self.maze = None self.rat_pos = None self.steps = 0 self.start_time = 0 self.visited = set() def load_maze(self, level): """根据难度级别加载迷宫""" filename = f'level{level}.txt' if not os.path.exists(filename): # 如果迷宫文件不存在,则生成 if level == 1: size = 12 elif level == 2: size = 20 else: size = 40 maze = MazeGenerator.generate_maze(size, size) np.savetxt(filename, maze, fmt='%d') else: maze = np.loadtxt(filename, dtype=int) self.maze = maze self.rat_pos = tuple(np.argwhere(maze == 2)[0]) # 初始位置 self.steps = 0 self.start_time = time.time() self.visited = set([self.rat_pos]) return maze def print_maze(self): """打印迷宫和老鼠当前位置""" os.system('cls' if os.name == 'nt' else 'clear') # 清屏 print(f"步数: {self.steps} | 用时: {time.time() - self.start_time:.1f}秒") for i, row in enumerate(self.maze): line = '' for j, cell in enumerate(row): if (i, j) == self.rat_pos: line += '🐭' # 老鼠位置 elif (i, j) in self.visited: line += '· ' # 已访问路径 elif cell == 0: line += ' ' # 路径 elif cell == 1: line += '██' # 墙 elif cell == 2: line += '🚪' # 起点 elif cell == 3: line += '🏁' # 终点 print(line) def move_rat(self, direction): """根据方向移动老鼠""" dx, dy = 0, 0 if direction == 'up': dx = -1 elif direction == 'down': dx = 1 elif direction == 'left': dy = -1 elif direction == 'right': dy = 1 new_pos = (self.rat_pos[0] + dx, self.rat_pos[1] + dy) # 检查移动是否有效 if (0 <= new_pos[0] < self.maze.shape[0] and 0 <= new_pos[1] < self.maze.shape[1] and self.maze[new_pos] != 1): # 不是墙 self.rat_pos = new_pos self.steps += 1 self.visited.add(new_pos) return True return False def is_completed(self): """检查是否到达终点""" return self.maze[self.rat_pos] == 3 def bfs_solve(self): """使用BFS算法自动求解迷宫""" start = tuple(np.argwhere(self.maze == 2)[0]) end = tuple(np.argwhere(self.maze == 3)[0]) # BFS寻路 queue = deque([start]) visited = {start: None} # 记录路径 while queue: current = queue.popleft() if current == end: break # 探索四个方向 for dx, dy in [(0, 1), (1, 0), (0, -1), (-1, 0)]: next_pos = (current[0] + dx, current[1] + dy) if (0 <= next_pos[0] < self.maze.shape[0] and 0 <= next_pos[1] < self.maze.shape[1] and self.maze[next_pos] != 1 and next_pos not in visited): queue.append(next_pos) visited[next_pos] = current # 回溯路径 if end not in visited: return [] # 没有找到路径 path = [] current = end while current != start: path.append(current) current = visited[current] path.reverse() return path # 键盘交互模式 def keyboard_mode(level): game = MazeGame() game.load_maze(level) print("使用方向键移动老鼠,🐭代表老鼠,🚪起点,🏁终点") print("按ESC键退出游戏") game.print_maze() try: while True: key = input("方向键 (w=上, s=下, a=左, d=右): ").lower() if key == 'esc': break direction = None if key == 'w': direction = 'up' elif key == 's': direction = 'down' elif key == 'a': direction = 'left' elif key == 'd': direction = 'right' if direction and game.move_rat(direction): game.print_maze() # 检查是否到达终点 if game.is_completed(): print(f"恭喜!老鼠成功走出迷宫!步数: {game.steps}, 用时: {time.time() - game.start_time:.1f}秒") break except KeyboardInterrupt: print("\n游戏已退出") # 自动求解模式 def auto_solve(level): game = MazeGame() game.load_maze(level) print("正在自动求解迷宫...") path = game.bfs_solve() if not path: print("没有找到解决方案!") return # 显示初始状态 game.print_maze() time.sleep(1) # 逐步显示路径 for i, pos in enumerate(path): game.rat_pos = pos game.steps = i + 1 game.print_maze() time.sleep(0.1) print(f"自动求解完成!步数: {len(path)}, 用时: {time.time() - game.start_time:.1f}秒") # 主程序 def main(): print("=== 电子老鼠走迷宫游戏 ===") print("难度级别:") print("1. 简单 (12x12)") print("2. 中等 (20x20)") print("3. 困难 (40x40)") while True: try: level = int(input("请选择难度级别 (1-3): ")) if level in [1, 2, 3]: break else: print("无效的难度选择,请重新输入!") except ValueError: print("请输入一个有效的数字 (1-3)!") print("\n游戏模式:") print("1. 键盘交互") print("2. 自动求解") while True: try: mode = int(input("请选择模式 (1-2): ")) if mode in [1, 2]: break else: print("无效的模式选择,请重新输入!") except ValueError: print("请输入一个有效的数字 (1-2)!") if mode == 1: keyboard_mode(level) elif mode == 2: auto_solve(level) if __name__ == "__main__": main() 帮我完善一下这个代码
06-15
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值