迷宫问题
题意:由0和1 构成迷宫,只有0可以走,请输出,从{0,0}到{4,4}的最短路径
思路:利用广搜,搜索时并且存储有用路径,此时的路径需要存进当前结构中,因为程序过程中, 头会被弹出,无法回溯
特别注意格式,逗号后还有个空格
#include<iostream>
#include<cstring>
#include<cstdio>
#include<cmath>
#include<queue>
#include<stack>
#define x first
#define y second
#define met(a,b) memset(a,b,sizeof a);
using namespace std;
typedef long long ll;
const int N=1e6+10;
int xx[4][2]= {{0,1},{0,-1},{-1,0},{1,0}};//四个方向
//int xx[8][2]= {{-1,0},{0,-1},{1,0},{0,1},{1,1},{-1,1},{-1,-1},{1,-1}};//八个方向
//int xx[8][2]= {{2,1},{-2,1},{1,2},{1,-2},{2,-1},{-2,-1},{-1,2},{-1,-2}};//马的八个方向
//int xx[6][3]= {{1,0,0},{-1,0,0},{0,1,0},{0,-1,0},{0,0,1},{0,0,-1}};//三维方向
int a[1005][1005];
int book[1005][1005];
int n,m;
int res;
int f;
struct node {
int x,y,s;
pair<int,int>lu[50];
};
node start,pre,nt;
queue<node>q;
void bfs(int x,int y) {
start.x=x;
start.y=y;
start.s=1;
start.lu[start.s]= {1,1};
q.push(start);
while(!q.empty()) {
int xt,yt;
pre=q.front();
q.pop();
if(pre.x==5&&pre.y==5) {
for(int j=1; j<=pre.s; ++j) {
printf("(%d, %d)\n",pre.lu[j].x-1,pre.lu[j].y-1);
}
return ;
}
for(int i=0; i<4; i++) {
xt=pre.x+xx[i][0];
yt=pre.y+xx[i][1];
nt=pre;
nt.s++;
if(xt<1||xt>5||yt<1||yt>5)continue;
if((!a[xt][yt])&&(!book[xt][yt])) {
book[xt][yt]=1;
nt.x=xt;
nt.y=yt;
nt.lu[nt.s]= {xt,yt};
q.push(nt);
}
}
}
}
int main() {
for(int i=1; i<=5; i++) {
for(int j=1; j<=5; j++) {
cin>>a[i][j];
}
}
met(book,0);
book[1][1]=1;
bfs(1,1);
// q.pop();
// cout<<q.front().s;
}
此时数据较水,直接输出样例也可