T1 T628045 迷宫问题
一道 求最短路但是要存储路径的题。
我就在怎么存储路径上卡了好久。。。
还有,
做了一半才想起来,之前写过的 好像和这个差不多!都可以用递归输出保存的数据!
所以把其他地方改成 就行啦~
#include<bits/stdc++.h>
typedef long long ll;
using namespace std;
const int N=10+10;
struct node{
int x,y,step;
}pre[N][N];
queue<node>q;
int fx[]={0,0,1,0,-1};
int fy[]={0,1,0,-1,0};
int a[N][N];
bool v[N][N];
void print(int x,int y){
if(x==0&&y==0){
cout<<"(0, 0)";
return;
}
print(pre[x][y].x,pre[x][y].y);
printf("\n(%d, %d)",x,y);
}
void bfs(int x,int y){
v[x][y]=1;
q.push({x,y,0});
while(!q.empty()){
node t=q.front();
q.pop();
if(t.x==4&&t.y==4){
print(t.x,t.y);
return;
}
for(int i=1;i<=4;i++){
int tx=t.x+fx[i];
int ty=t.y+fy[i];
if(tx>=0&&tx<=4&&ty>=0&&ty<=4&&a[tx][ty]!=1&&v[tx][ty]==0){
q.push({tx,ty,t.step});
pre[tx][ty]={t.x,t.y};
v[tx][ty]=1;
}
}
}
}
int main(){
for(int i=0;i<=4;i++){
for(int j=0;j<=4;j++){
cin>>a[i][j];
}
}
bfs(0,0);
return 0;
}T2 T628044 迷宫之输出路径-困难版
不就是上一题的升级版嘛。。。
多加一个参数就行了
#include<bits/stdc++.h>
typedef long long ll;
using namespace std;
const int N=5e3+10;
struct node{
int x,y;
char qwq;
}pre[N][N];
queue<node>q;
int fx[]={0,1,0,0,-1};
int fy[]={0,0,-1,1,0};
int n,m;
bool v[N][N],f;
char a[N][N];
void print(int x,int y){
if(x==1&&y==1)return;
print(pre[x][y].x,pre[x][y].y);
if(pre[x][y].qwq!=' ')cout<<pre[x][y].qwq;
}
void bfs(int x,int y){
v[x][y]=1;
q.push({x,y,' '});
while(!q.empty()){
node t=q.front();
q.pop();
if(t.x==n&&t.y==m){
print(t.x,t.y);
f=1;
return;
}
for(int i=1;i<=4;i++){
int tx=t.x+fx[i];
int ty=t.y+fy[i];
if(tx>=1&&tx<=n&&ty>=1&&ty<=m&&a[tx][ty]=='0'&&v[tx][ty]==0){
char awa=0;
if(i==1)awa='D';
else if(i==2)awa='L';
else if(i==3)awa='R';
else awa='U';
q.push({tx,ty,awa});
pre[tx][ty]={t.x,t.y,awa};
v[tx][ty]=1;
}
}
}
}
int main(){
cin>>n>>m;
for(int i=1;i<=n;i++){
for(int j=1;j<=m;j++){
cin>>a[i][j];
}
}
bfs(1,1);
if(f==0)cout<<-1;
return 0;
}记得要输出-1!
T3 P2360 地下城主
三维。。。
把方向数组改成6个,多加一个位置参数,数组改成三维就行了,其他地方都差不多
#include<bits/stdc++.h>
typedef long long ll;
using namespace std;
const int N=30+10;
int n,m,sx,sy,sz,ex,ey,ez,v[N][N][N],k;
char a[N][N][N];
int fx[]={0,0,1,0,-1,0,0};
int fy[]={0,1,0,-1,0,0,0};
int fz[]={0,0,0,0,0,1,-1};
struct node{
int x,y,z,step;
};
queue<node>q;
void bfs(int x,int y,int z){
v[x][y][z]=1;
q.push({x,y,z,0});
while(!q.empty()){
node t=q.front();
q.pop();
if(t.x==ex&&t.y==ey&&t.z==ez){
printf("Escaped in %d minute(s).",t.step);
exit(0);
}
for(int i=1;i<=6;i++){
int tx=t.x+fx[i];
int ty=t.y+fy[i];
int tz=t.z+fz[i];
if(tx>=1&&tx<=n&&ty>=1&&ty<=m&&tz>=1&&tz<=k&&a[tx][ty][tz]!='#'&&v[tx][ty][tz]==0){
q.push({tx,ty,tz,t.step+1});
v[tx][ty][tz]=1;
}
}
}
return;
}
int main(){
cin>>n>>m>>k;
for(int i=1;i<=n;i++){
for(int j=1;j<=m;j++){
for(int l=1;l<=k;l++){
cin>>a[i][j][l];
if(a[i][j][l]=='S'){
sx=i;
sy=j;
sz=l;
}
if(a[i][j][l]=='E'){
ex=i;
ey=j;
ez=l;
}
}
}
}
bfs(sx,sy,sz);
cout<<"Trapped!";
return 0;
}bye~