hdu 1240 Asteroids! (BFS)

题意:三维的空间,给定起点和终点,要求最少的步数。

分析:一般的 广搜,就是读入这个图有点麻烦,弄晕了

#include<iostream>
#include<algorithm>
#include<queue>
using namespace std;
char map[11][11][11];
bool vis[11][11][11];
int dir[6][3]={{1,0,0},{-1,0,0},{0,1,0},{0,-1,0},{0,0,1},{0,0,-1}};
int n,ans;
int ei,ej,ez;
struct node
{
	int x,y,z,cnt;
	node(int a=0,int b=0,int c=0,int d=0):x(a),y(b),z(c),cnt(d){}
};
void BFS(node f)
{
	queue<node> Q;
	Q.push(f);
	node temp;
	while(!Q.empty())
	{
		temp=Q.front();
		Q.pop();
		if(temp.x==ei && temp.y==ej && temp.z==ez)
		{
			ans=temp.cnt;
			return ;
		}
		for(int k=0;k<6;k++)
		{
			int x=temp.x+dir[k][0];
			int y=temp.y+dir[k][1];
			int z=temp.z+dir[k][2];
			if(x<0 || x>=n || y<0|| y>=n || z<0||z>=n || vis[x][y][z]||map[x][y][z]=='X')
				continue;
			vis[x][y][z]=1;
			Q.push(node(x,y,z,temp.cnt+1));
		}
	}
}
int main()
{
	char str[10];
	int si,sj,sz;
	while(scanf("%s %d",str,&n)==2)
	{
		for(int k=0;k<n;k++)
		for(int i=0;i<n;i++)
		{
			getchar();
			for(int j=0;j<n;j++)
			{
				scanf("%c",&map[i][j][k]);
			}
		}
		scanf("%d %d %d",&si,&sj,&sz);
		scanf("%d %d %d",&ei,&ej,&ez);
		scanf("%s",str);
		memset(vis,0,sizeof(vis));
		vis[si][sj][sz]=1;
		node f=node(si,sj,sz,0);
		ans=-1;
		BFS(f);
		if(ans==-1)
			puts("NO ROUTE");
		else 
			printf("%d %d\n",n,ans);
	}
	return 0;
}
原文地址:https://www.cnblogs.com/nanke/p/2283335.html