poj3984 输出路径
第一次做输出路径的搜索题 这道题没有想到一个好办法
手写队列 然后记录前一个在队列中的位置 居然没有想到这个办法
这道题输出路径有多个方法 如在地图中存储每个点的转向 时间效率 和空间效率 都和上面是一样的
#include<cstdio>
#include<iostream>
#define N 5
using namespace std;
struct note
{
int x,y,pre; //存放坐标,前一个节点在队列中的位置
} que[100];
int map[N][N];
int Nx[4]= {1,-1,0,0};
int Ny[4]= {0,0,-1,1};
int start=0,end=1; //用que结构体数组模拟一个队列
void print(int s)
{
if(que[s].pre!=-1)
{
print(que[s].pre);
cout<<"("<<que[s].x<<", "<<que[s].y<<")"<<endl;
}
}
void bfsMap(int x,int y)
{
que[start].pre=-1;
que[start].x=x;
que[start].y=y;
while(start<end)
{
for(int i=0; i<4; i++)
{
int a=Nx[i]+que[start].x;
int b=Ny[i]+que[start].y;
if(a<0 || b<0 || a>=N || b>=N || map[a][b])//如果出界或者遇到墙或者已经被访问
continue;
map[a][b]=-1;//设置已经访问过
que[end].pre=start;
que[end].x=a;
que[end++].y=b;
if(a==N-1 && b==N-1)
print(start);
}
start++;
}
}
int main()
{
int i,j;
for(i=0; i<N; i++)
for(j=0; j<N; j++)
scanf("%d",&map[i][j]);
cout<<"(0, 0)"<<endl;
bfsMap(0,0);
cout<<"("<<N-1<<", "<<N-1<<")"<<endl;
return 0;
}