迷宫问题 (最短路径保存输出)


定义一个二维数组: 

int maze[5][5] = {

0, 1, 0, 0, 0,

0, 1, 0, 1, 0,

0, 0, 0, 0, 0,

0, 1, 1, 1, 0,

0, 0, 0, 1, 0,

};


它表示一个迷宫,其中的1表示墙壁,0表示可以走的路,只能横着走或竖着走,不能斜着走,要求编程序找出从左上角到右下角的最短路线。

 

Input一个5 × 5的二维数组,表示一个迷宫。数据保证有唯一解。Output左上角到右下角的最短路径,格式如样例所示。Sample Input

0 1 0 0 0
0 1 0 1 0
0 0 0 0 0
0 1 1 1 0
0 0 0 1 0

Sample Output

(0, 0)
(1, 0)
(2, 0)
(2, 1)
(2, 2)
(2, 3)
(2, 4)
(3, 4)
(4, 4)



#include <iostream> #include <algorithm> #include <cstdio> #include <string> #include <cstring> #include <cstdlib> #include <map> #include <vector> #include <set> #include <queue> #include <stack> #include <cmath> #include <deque>
using namespace std; #define ull unsigned long long
#define lli long long
#define pq priority_queue<int>
#define pql priority_queue<ll>
#define pqn priority_queue<node>
#define v vector<int>
#define vl vector<ll>
#define read(x) scanf("%d",&x)
#define lread(x) scanf("%lld",&x);
#define pt(x) printf("%d\n",(x))
#define YES printf("YES\n");
#define NO printf("NO\n");
#define gcd __gcd
#define out(x) cout<<x<<endl;
#define over cout<<endl;
#define rep(j,k) for (int i = (int)(j); i <= (int)(k); i++)
#define input(k,m) for (int i = 1; i <= (int)(k); i++)  for(int j=1;j<=m;j++) {scanf("%d",&a[i][j]) ; }
#define mem(s,t) memset(s,t,sizeof(s))
#define ok return 0;
#define TLE std::ios::sync_with_stdio(false);cin.tie(NULL);cout.tie(NULL);
#define mod(x) ((x)%9973)
#define test cout<<"     ++++++      "<<endl;
#define MAXN 0x3f3f3f3f
#define pi acos(-1.0)
//二叉树
#define lson rt<<1, l, m
#define rson rt<<1|1, m+1, r
//线段树
#define ls now<<1
#define rs now<<1|1
int dir[4][2] = {1,0,-1,0,0,1,0,-1}; //单位移动 //int dir[8][2] = {2,1,2,-1,-2,1,-2,-1,1,2,1,-2,-1,2,-1,-2};
int t,n,m,k,x,y,col,ex,ey,ans,cnt; lli a[202][202],b[202][202]; int vis[11][11]; typedef struct node {    int x,y,px,py;}node; node dp[5][5],p; void BFS() { mem(vis,0); queue<node>q; dp[1][1].x=dp[1][1].y=0; q.push(dp[1][1]); vis[1][1]=1; while(!q.empty()) { p=q.front(); //cout<<p.x<< " " <<p.y<<" "<<endl;
 q.pop(); if(p.x==5 && p.y==5) return; for(int i=0;i<4;i++) { int nx=p.x+dir[i][0]; int ny=p.y+dir[i][1]; if(nx<0 || ny<0 || nx>=5 || ny>=5) continue; if(!a[nx][ny]) { //cout<<nx<<" nx "<<ny<<endl; //cout<<p.x<<" p.x++++ "<<p.y<<endl;
                a[nx][ny] = 1; dp[nx][ny].x=nx; dp[nx][ny].y=ny; dp[nx][ny].px=p.x; dp[nx][ny].py=p.y; q.push(dp[nx][ny]); } } } } void outdp(int x,int y) { //cout<<x<<" ----- "<<y<<endl;
    if(x==0 &&y==0) { cout<<"("<<dp[1][1].x<<", "<<dp[1][1].y<<")"<<endl; return; } int nx=dp[x][y].px; int ny=dp[x][y].py; //cout<<nx<<" "<<ny<<endl;
 outdp(nx,ny); cout<<"("<<dp[x][y].x<<", "<<dp[x][y].y<<")"<<endl; } int main() { for(int i=0;i<5;i++) for(int j=0;j<5;j++) cin>>a[i][j]; BFS(); outdp(4,4); ok; }

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM