电子老鼠闯迷宫(广度优先搜索)

本文介绍了一种解决迷宫最短路径问题的算法实现,通过定义方向坐标关系,使用队列思想进行广度优先搜索,并记录路径。适用于12×12的迷宫,从特定起点到终点寻找最短路线。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Description

如下图12×12方格图,找出一条自入口(2,9)到出口(11,8)的最短路径。 
电子老鼠闯迷宫(广度优先搜索)

Input

 

Output

 

Sample Input

 

12  //迷宫大小
2 9 11 8 //起点和终点
1 1 1 1 1 1 1 1 1 1 1 1  //邻接矩阵,0表示通,1表示不通
1 0 0 0 0 0 0 1 0 1 1 1
1 0 1 0 1 1 0 0 0 0 0 1
1 0 1 0 1 1 0 1 1 1 0 1
1 0 1 0 0 0 0 0 1 0 0 1
1 0 1 0 1 1 1 1 1 1 1 1
1 0 0 0 1 0 1 0 0 0 0 1
1 0 1 1 1 0 0 0 1 1 1 1
1 0 0 0 0 0 1 0 0 0 0 1
1 1 1 0 1 1 1 1 0 1 0 1
1 1 1 1 1 1 1 0 0 1 1 1
1 1 1 1 1 1 1 1 1 1 1 1

 

Sample Output

 

(2,9)->(3,9)->(3,8)->(3,7)->(4,7)->(5,7)->(5,6)->(5,5)->(5,4)->(6,4)->(7,4)->(7,3)->(7,2)->(8,2)->(9,2)->(9,3)->(9,4)->(9,5)->(9,6)->(8,6)->(8,7)->(8,8)->(9,8)->(9,9)->(10,9)->(11,9)->(11,8) 
27


解题思路:先定义两个常量数组,表明电子老鼠可能走的方向坐标关系,然后读入数据,用队列的思想,最后根据二叉树的父节点记录来进行输出。


程序:
const
  maxn=12;
  wayn=4;
  dx:array[1..wayn] of integer=(-1,0,1,0);
  dy:array[1..wayn] of integer=(0,1,0,-1);

var
  px,py,qx,qy,s,last:integer;
  a:array[0..maxn+1,0..maxn+1] of integer;
  father:array[1..maxn*maxn] of integer;
  state:array[1..maxn*maxn,1..2] of integer;

procedure init;
  var
    i,j,n:integer;
  begin
    readln(n);
    read(px,py);
    readln(qx,qy);
    for i:=1 to n do
      begin
        for j:=1 to n do
          read(a[i,j]);
        readln;
      end;
end;

function check(x,y:integer):boolean;
  begin
    check:=true;
    if (x<1) or (x>12) or (y<1) or (y>12) then check:=false;
    if a[x,y]=1 then check:=false;
  end;

procedure print(x:integer);
  begin
    if x=0 then exit;
    inc(s);
    print(father[x]);
    if x<>last then write('(',state[x,1],',',state[x,2],')->')
      else writeln('(',state[x,1],',',state[x,2],')')
end;

procedure bfs;
  var
    tail,head,k,i:integer;
  begin
    head:=0;
    tail:=1;state[1,1]:=px;state[1,2]:=py;
    father[1]:=0;
    repeat
      head:=head+1;
      for k:=1 to wayn do
        if check(state[head,1]+dx[k],state[head,2]+dy[k])
          then begin
                 tail:=tail+1;
                 father[tail]:=head;
                 state[tail,1]:=state[head,1]+dx[k];
                 state[tail,2]:=state[head,2]+dy[k];
                 a[state[tail,1],state[tail,2]]:=1;
                 if (state[tail,1]=qx) and (state[tail,2]=qy)
                   then begin
                          s:=0;
                          last:=tail;
                          print(tail);
                          writeln(s);
                          tail:=0;
                        end;
              end;
    until head>=tail;
end;


begin
  init;
  bfs;
end.
### 关于电子老鼠迷宫的图表与模拟 #### 深度优先搜索 (DFS) 构建迷宫 深度优先搜索是一种经典的算法,可以用来生成随机迷宫。其核心思想是从某个起点出发,沿着一条路径尽可能深入探索,直到无法继续前进为止,随后回溯并尝试其他方向[^1]。 以下是 DFS 算法的核心逻辑: ```python import random def dfs_maze(grid, x, y): directions = [(0, 1), (1, 0), (0, -1), (-1, 0)] random.shuffle(directions) for dx, dy in directions: nx, ny = x + dx * 2, y + dy * 2 if 0 <= nx < len(grid) and 0 <= ny < len(grid[0]) and grid[nx][ny] == 'wall': grid[x + dx][y + dy] = 'path' grid[nx][ny] = 'path' dfs_maze(grid, nx, ny) ``` 此代码片段展示了如何通过递归方式构建迷宫中的通路,并移除墙壁以形成连贯的路径。 --- #### 基础搜索算法解决迷宫问题 为了实现机器人自动走出迷宫的功能,通常会采用广度优先搜索 (BFS) 或 A* 算法来找到最短路径。这些方法能够有效地规划从入口到出口的最佳路线[^3]。 以下是一个简单的 BFS 实现示例: ```python from collections import deque def bfs_solve(maze, start, goal): queue = deque([(start, [])]) visited = set() while queue: current, path = queue.popleft() if current == goal: return path + [current] if current not in visited: visited.add(current) neighbors = get_neighbors(maze, current) for neighbor in neighbors: queue.append((neighbor, path + [current])) return None ``` 上述代码利用队列结构逐步扩展节点,记录访问过的状态以避免重复计算。 --- #### 使用 Deep Q-Learning 的强化学习解决方案 对于更复杂的场景,Deep Q-Learning 是一种有效的策略,它允许机器人通过试错机制逐渐学会最优行为模式。这种方法尤其适合动态环境下的决策支持[^2]。 模型训练过程如下所示: ```python class DQNAgent: def __init__(self, state_size, action_size): self.state_size = state_size self.action_size = action_size self.memory = [] self.gamma = 0.95 self.epsilon = 1.0 self.learning_rate = 0.001 self.model = self._build_model() def _build_model(self): model = Sequential([ Dense(24, input_dim=self.state_size, activation='relu'), Dense(24, activation='relu'), Dense(self.action_size, activation='linear') ]) model.compile(loss="mse", optimizer=Adam(lr=self.learning_rate)) return model def act(self, state): if np.random.rand() <= self.epsilon: return random.randrange(self.action_size) act_values = self.model.predict(state) return np.argmax(act_values[0]) def replay(self, batch_size): minibatch = random.sample(self.memory, batch_size) for state, action, reward, next_state, done in minibatch: target = reward if not done: target += self.gamma * np.amax(self.model.predict(next_state)[0]) target_f = self.model.predict(state) target_f[0][action] = target self.model.fit(state, target_f, epochs=1, verbose=0) ``` 这段代码定义了一个基于神经网络的学习代理,能够在多次迭代过程中优化动作选择策略。 --- #### 数据可视化工具推荐 针对迷宫及其求解过程的可视化需求,可借助 Matplotlib 和 Pygame 库完成交互式动画效果。例如: - **Matplotlib**: 提供静态图像绘制功能,适用于展示最终结果。 - **Pygame**: 支持实时渲染,便于观察每一步的变化情况。 以下是使用 Pygame 绘制迷宫的一个简单例子: ```python import pygame pygame.init() screen = pygame.display.set_mode((800, 600)) running = True while running: screen.fill((255, 255, 255)) # 白色背景 for event in pygame.event.get(): if event.type == pygame.QUIT: running = False # 绘制迷宫网格 cell_size = 40 rows, cols = 15, 20 for i in range(rows): for j in range(cols): rect = pygame.Rect(j * cell_size, i * cell_size, cell_size, cell_size) pygame.draw.rect(screen, (0, 0, 0), rect, 1) pygame.display.flip() pygame.quit() ``` 该脚本创建了一张带有边框线条的二维平面图,可用于表示任意大小的迷宫布局。 ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值