【NOI】6264 走出迷宫

本文介绍了一种解决迷宫最短路径问题的算法实现,通过广度优先搜索(BFS)策略找到从起点到终点的最短路径,并详细展示了算法的具体实现过程。

描述
当你站在一个迷宫里的时候,往往会被错综复杂的道路弄得失去方向感,如果你能得到迷宫地图,事情就会变得非常简单。
假设你已经得到了一个n*m的迷宫的图纸,请你找出从起点到出口的最短路。

输入
第一行是两个整数n和m(1<=n,m<=100),表示迷宫的行数和列数。
接下来n行,每行一个长为m的字符串,表示整个迷宫的布局。字符’.’表示空地,’#’表示墙,’S’表示起点,’T’表示出口。
输出
输出从起点到出口最少需要走的步数。

-

依旧是隔壁的走迷宫板子
记个起点终点就行

#include<cstdio>
#include<cstring>
#include<queue>
using namespace std;

int r,c;
int X[4]={0,1,0,-1},
    Y[4]={1,0,-1,0};
bool a[200][200];

int main()
{
    queue<int> x,y,b,f;
    int n,m;
    b.push(0);f.push(4);

    scanf("%d%d",&r,&c);
    memset(a,0,sizeof(a));
    for(int i=1;i<=r;++i)
    {
        char C;
        scanf("%c",&C);//去掉前面的空格 
        for(int j=1;j<=c;++j)
        {
          scanf("%c",&C);
          if(C=='#') a[i][j]=1;
          else
          if(C=='S') {x.push(i);y.push(j);}
          else
          if(C=='T') {n=i;m=j;}
        }
    }
    //printf("%d %d\n%d %d\n",x.front(),y.front(),n,m);
    do
    {
        for(int i=0;i<4;++i)
          if(f.front()!=(i+2)%4)
          {
            int xx=x.front()+X[i],yy=y.front()+Y[i];
            if(!a[xx][yy]&&xx>=1&&xx<=r&&yy>=1&&yy<=c)
            {
                b.push(b.front()+1);
                x.push(xx);y.push(yy);
                a[xx][yy]=1;f.push(i);
                if(xx==n&&yy==m)
                {
                    printf("%d",b.back());
                    return 0;
                }
            }
          }
        x.pop();y.pop();
        b.pop();f.pop();
    }
    while(!x.empty());
    return 0;
}
### Python 实现迷宫求解算法 #### 使用递归回溯法解决迷宫问题 一种常见的方法是利用递归回溯来探索所有可能的路径直至找到出口。这种方法简单直观,适合初学者理解基本原理。 ```python def solve_maze(maze, start, end): directions = [(0, 1), (1, 0), (0, -1), (-1, 0)] # 右 下 左 上 def is_valid(x, y): if not (0 <= x < len(maze) and 0 <= y < len(maze[0])): return False if maze[x][y] != 0: # 非通路 return False return True def backtrack(path, pos): if pos == end: path.append(pos) return True for dx, dy in directions: next_pos = (pos[0]+dx, pos[1]+dy) if is_valid(*next_pos): maze[next_pos[0]][next_pos[1]] = 2 # 标记为已访问 if backtrack(path, next_pos): path.append(pos) return True maze[next_pos[0]][next_pos[1]] = 0 # 恢复现场 return False solution_path = [] if backtrack(solution_path, start): print("成功走出迷宫") print(f"路径为:{solution_path[::-1]}") # 输出逆序后的列表作为正确路径 else: print("无法到达终点") maze_example = [ [1, 1, 1, 1], [0, 0, 1, 1], [1, 0, 0, 1], [1, 1, 0, 0] ] solve_maze(maze_example, (3, 2), (0, 0)) ``` 此段代码定义了一个`solve_maze()`函数用于尝试从起点走到终点,并打印出解决方案[^3]。 #### 利用广度优先搜索(BFS) 另一种有效的方法就是采用BFS遍历整个图结构,在遇到障碍物时停止前进并转向其他方向继续探索新的分支,直到抵达目标位置为止。 ```python from collections import deque def bfs_solve_maze(maze, start, goal): queue = deque([start]) visited = set() parent_map = {start: None} while queue: current = queue.popleft() if current == goal: break neighbors = get_neighbors(current, maze) for neighbor in neighbors: if neighbor not in visited: visited.add(neighbor) parent_map[neighbor] = current queue.append(neighbor) path = reconstruct_path(parent_map, start, goal) return path def get_neighbors(position, grid): rows, cols = len(grid), len(grid[0]) row, col = position possible_moves = [] moves = ((-1, 0),(1, 0),(0, -1),(0, 1)) for dr, dc in moves: new_row, new_col = row + dr, col + dc if 0 <= new_row < rows and 0 <= new_col < cols and grid[new_row][new_col]==0 : possible_moves.append((new_row,new_col)) return possible_moves def reconstruct_path(came_from, start, target): reverse_path = [] at = target while at != start: reverse_path.append(at) at = came_from[at] reverse_path.reverse() return [start] + reverse_path bfs_solution = bfs_solve_maze([ [1, 1, 1, 1], [0, 0, 1, 1], [1, 0, 0, 1], [1, 1, 0, 0]], (3, 2), (0, 0) ) print(bfs_solution) ``` 这段程序实现了基于队列的数据结构来进行层次化扩展节点的过程,从而保证最先被发现的目标即是最优解之一[^1]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值