重点这题是三维的。要找好始末位置!
做了这么久才发现了一道在最优解的问题上bfs dfs有矛盾的题。
dfs交了N发过不去。bfs写了两发就过了。
#include <iostream>
#include <stdio.h>
#include <queue>
#include <cstring>
using namespace std;
struct node
{
int x,y,z,step;
};
int mp[55][55][55];
int vis[55][55][55];
int yes;
int ans=999999;
int over;
int A,B,C;
queue <node> s;
void bfs()
{
int step=0;
node t;
t.x=1;
t.y=1;
t.z=1;
t.step=0;
s.push(t);
vis[1][1][1]=1;
while(!s.empty())
{
t=s.front();
s.pop();
if(t.step>over)
{
printf("-1\n");
return ;
}
if(t.z==A&&t.x==B&&t.y==C)
{
printf("%d\n",t.step);
return ;
}
int next[10][5]={{1,0,0},{-1,0,0},{0,1,0},{0,-1,0},{0,0,1},{0,0,-1}};
for(int i=0;i<6;i++)
{
node temp=t;
temp.z+=next[i][0];
temp.x+=next[i][1];
temp.y+=next[i][2];
if(temp.x<1||temp.y<1||temp.z<1||temp.x>B||temp.y>C||temp.z>A||vis[temp.z][temp.x][temp.y]!=0||mp[temp.z][temp.x][temp.y])
continue;
temp.step++;
vis[temp.z][temp.x][temp.y]=1;
s.push(temp);
}
}
printf("-1\n");
return ;
}
int main()
{
int K;
scanf("%d",&K);
while(K--)
{
memset(vis,0,sizeof(vis));
scanf("%d%d%d%d",&A,&B,&C,&over);
for(int i=1;i<=A;i++)
{
for(int n=1;n<=B;n++)
{
for(int m=1;m<=C;m++)
{
scanf("%d",&mp[i][n][m]);
}
}
}
bfs();
}
return 0;
}
/*
1
2 2 2 3
0 0
0 1
0 0
0 1
*/