迷宫问题三种种解法(A*算法+BFS+双向广搜)

题目描述

小明置身于一个迷宫,请你帮小明找出从起点到终点的最短路程。
小明只能向上下左右四个方向移动。

输入格式

输入包含多组测试数据。输入的第一行是一个整数T,表示有T组测试数据。
每组输入的第一行是两个整数N和M(1<=N,M<=100)。
接下来N行,每行输入M个字符,每个字符表示迷宫中的一个小方格。
字符的含义如下:
‘S’:起点
‘E’:终点
‘-’:空地,可以通过
‘#’:障碍,无法通过
输入数据保证有且仅有一个起点和终点。

输出格式

对于每组输入,输出从起点到终点的最短路程,如果不存在从起点到终点的路,则输出-1。

样例输入

1
5 5
S-###
-----
##---
E#---
---##

样例输出

一、A*算法 

#include<iostream>
#include<queue>
#include<vector>
#include<cstring>
#include<unordered_map>
#define x first
#define y second
using namespace std;
const int N=105;
char a[N][N];
int n,m,dist[N][N],sx,sy,ex,ey;
bool st[N][N];
typedef pair<int,int> PII;
typedef pair<int,PII> PIII;
typedef pair<int,PIII> PIIII;
int ne[4][2]={{0,1},{0,-1},{1,0},{-1,0}};
void Dijkstra()
{
    memset(st,false,sizeof st);
   priority_queue<PIII,vector<PIII>,greater<PIII>> heap;
   heap.push({0,{ex,ey}});
   memset(dist,0x3f,sizeof dist);
   dist[ex][ey]=0;
   while(heap.size())
   {
       auto it=heap.top();heap.pop();
       int xx=it.y.x,yy=it.y.y,distance=it.x;
       if(st[xx][yy]) continue;
       st[xx][yy]=true;
       for(int i=0;i<=3;i++)
       {
           int tx=xx+ne[i][0],ty=yy+ne[i][1];
           if(!st[tx][ty]&&tx>=0&&tx<n&&ty>=0&&ty<m&&a[tx][ty]!='#')
           {
               if(dist[tx][ty]>distance+1)
               {
                   dist[tx][ty]=distance+1;
                   heap.push({dist[tx][ty],{tx,ty}});
               }
           }
       }
   }
}
int astar()
{
    if(dist[sx][sy]==0x3f3f3f3f) return -1;
    priority_queue<PIIII,vector<PIIII>,greater<PIIII>> heap;
    heap.push({dist[sx][sy],{0,{sx,sy}}});
    memset(st,false,sizeof st);
    while(heap.size())
    {
        auto it=heap.top();heap.pop();
        int distance=it.y.x,xx=it.y.y.x,yy=it.y.y.y;
        if(xx==ex&&yy==ey) return distance;
        if(st[xx][yy]) continue;
        st[xx][yy]=true;
        for(int i=0;i<=3;i++)
        {
            int tx=ne[i][0]+xx,ty=yy+ne[i][1];
            if(a[tx][ty]=='#') continue;
            if(!st[tx][ty]&&tx>=0&&tx<n&&ty>=0&&ty<m)
            {
                heap.push({distance+1+dist[tx][ty],{distance+1,{tx,ty}}});
            }
        }
    }
    return -1;
}
int main()
{
    int t;cin>>t;
    while(t--)
    {
        cin>>n>>m;
        memset(a,'\0',sizeof a);
        for(int i=0;i<n;i++)
        for(int j=0;j<m;j++)
        {
            cin>>a[i][j];
            if(a[i][j]=='S') sx=i,sy=j;
            if(a[i][j]=='E') ex=i,ey=j;
        }
        Dijkstra();
        cout<<astar()<<endl;
    }
}

二、BFSDFS省略不写,不是因为我太懒才不想写)

#include<iostream>
#include<cstring>
#include<queue>
#include<cstdlib>
using namespace std;
const int N=105;
typedef pair<int,int> PII;
char a[N][N];
int t,n,m,sx,sy,ex,ey;
int dist[N][N];
bool st[N][N];
int ne[4][2]={{1,0},{-1,0},{0,1},{0,-1}};
int BFS()
{
    queue<PII> q;
    q.push({sx,sy});
    memset(dist,0x3f,sizeof dist);
    memset(st,false,sizeof st);
    dist[sx][sy]=0;
    st[sx][sy]=true;
    while(q.size())
    {
        auto it=q.front();q.pop();
        int x=it.first,y=it.second;
        if(x==ex&&y==ey) return dist[x][y];
        for(int i=0;i<=3;i++)
        {
            int tx=x+ne[i][0],ty=y+ne[i][1];
            if(tx>=0&&tx<n&&ty>=0&&ty<m&&a[tx][ty]!='#'&&!st[tx][ty])
            {
                dist[tx][ty]=dist[x][y]+1;
                q.push({tx,ty});
                st[tx][ty]=true;
            }
        }
    }
    return -1;
}
int main()
{
    cin>>t;
    while(t--)
    {
        cin>>n>>m;
        memset(a,'\0',sizeof a);
        for(int i=0;i<n;i++)
        for(int j=0;j<m;j++)
        {
             cin>>a[i][j];
             if(a[i][j]=='S')
             sx=i,sy=j;
             if(a[i][j]=='E')
             ex=i,ey=j;
        }
        cout<<BFS()<<endl;
    }
    
}

三、双向广搜

#include<iostream>
#include<queue>
#include<cstring>
#include<unordered_map>
using namespace std;
const int N=105;
typedef pair<int,int> PII;
int da[N][N],db[N][N],n,m,t,sx,sy,ex,ey;
char a[N][N];
int ne[4][2]={{0,1},{0,-1},{1,0},{-1,0}};
int extend(queue<PII> &q,int da[][N],int db[][N])
{
    auto it=q.front();q.pop();
    int x=it.first,y=it.second;
    for(int i=0;i<=3;i++)
    {
      int tx=x+ne[i][0],ty=y+ne[i][1];
      if(tx>=0&&tx<n&&ty>=0&&ty<m&&a[tx][ty]!='#'&&da[tx][ty]==-1)
      {
          if(db[tx][ty]!=-1) return da[x][y]+db[tx][ty]+1;
         da[tx][ty]=da[x][y]+1;
         q.push({tx,ty});
      }
    }
    return -1;
}
int BFS()
{
    queue<PII> qa,qb;
    qa.push({sx,sy});
    qb.push({ex,ey});
    memset(da,-1,sizeof da);
    memset(db,-1,sizeof db);
    da[sx][sy]=0;db[ex][ey]=0;
    while(qa.size()&&qb.size())
    {
        int t;
        if(qa.size()<=qb.size()) t=extend(qa,da,db);
        else t=extend(qb,db,da);
        if(t!=-1) return t;
    }
    return -1;
}
int main()
{
    cin>>t;
    while(t--)
    {
        cin>>n>>m;
        memset(a,'\0',sizeof a);
        for(int i=0;i<n;i++)
        for(int j=0;j<m;j++)
        {
            cin>>a[i][j];
            if(a[i][j]=='S') sx=i,sy=j;
            if(a[i][j]=='E') ex=i,ey=j;
        }
        cout<<BFS()<<endl;
    }
}

  • 38
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
迷宫问题C语言中通常可以通过广度优先搜索(BFS)或深度优先搜索(DFS)算法来解决。这里我会提供一个简单的二维迷宫遍历的BFS解法示例。请注意,这只是一个基础版本,实际的迷宫可能需要处理边界条件、死路等复杂情况。 ```c #include <stdio.h> #include <stdlib.h> #include <stdbool.h> #define ROWS 5 // 迷宫行数 #define COLS 7 // 迷宫列数 #define WALL '#' // 二维数组表示迷宫 char maze[ROWS][COLS] = { {'#', '#', '#', '#', '#', '#', '#'}, {'#', ' ', ' ', '.', ' ', '#', '#'}, {'#', ' ', '.', ' ', '.', ' ', '#'}, {'#', ' ', '.', ' ', '.', ' ', '#'}, {'#', '#', '#', '#', '#', '#', '#'} }; // 用于存储路径的辅助数组 bool visited[ROWS][COLS]; // 遍历迷宫的函数 void bfs(int start_row, int start_col) { int rows = ROWS; int cols = COLS; queue<int> q; // 设置起点为已访问 visited[start_row][start_col] = true; q.push(start_row * cols + start_col); while (!q.empty()) { int row = q.front() / cols; int col = q.front() % cols; q.pop(); printf("(%d,%d) ", row, col); // 打印路径 // 检查上下左右邻居是否合法并未访问 if (row > 0 && maze[row-1][col] = true; q.push((row-1) * cols + col); } if (row < rows-1 && maze[row+1][col] != WALL && !visited[row+1][col]) { visited[row+1][col] = true; q.push((row+1) * cols + col); } if (col > 0 && maze[row][col-1] != WALL && !visited[row][col-1]) { visited[row][col-1] = true; q.push(row * cols + col - 1); } if (col < cols-1 && maze[row][col+1] != WALL && !visited[row][col+1]) { visited[row][col+1] = true; q.push(row * cols + col + 1); } } } int main() { bfs(1, 3); // 从起始位置 (1,3) 开始遍历 printf("\nEnd of path.\n"); return 0; } ```

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

SuperRandi

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值