题目地址:http://poj.org/problem?id=3984
思路:路径输出有2种方式,一种是用STL提供的queue,但是必须在结构体中加step或pre,来标记他本身的操作或上一个操作,第二种是手动写队列,通过数组下标来记录,这种简单
AC代码:
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <algorithm>
#include <queue>
#include <stack>
#include <map>
#include <cstring>
#include <climits>
#include <cmath>
#include <cctype>
const int inf = 0x7f7f7f7f;//2139062143
typedef long long ll;
using namespace std;
int map1[5][5];
int visit[30][30];
int pre[30];
struct node
{
int x;
int y;
}a[30];
int dir[4][2] = {{-1,0},{1,0},{0,-1},{0,1}};
bool judge(int x,int y)
{
if(x >=0 && x < 5 && y >= 0 && y < 5 && !visit[x][y] && !map1[x][y])
return true;
return false;
}
void print(int x)
{
int t = pre[x];
if(t == -1)
{
printf("(0, 0)\n");
return;
}
print(t);
printf("(%d, %d)\n",a[x].x,a[x].y);
}
void bfs()
{
int head = 0,tail = 1;
a[0].x = 0;
a[0].y = 0;
pre[0] = -1;
while(head < tail)
{
for(int i=0; i<4; i++)
{
int newx = a[head].x + dir[i][0];
int newy = a[head].y + dir[i][1];
if(a[head].x == 4 && a[head].y == 4)
{
print(head);
return;
}
if(judge(newx,newy))
{
visit[newx][newy] = 1;
pre[tail] = head;
a[tail].x = newx;
a[tail].y = newy;
tail++;
}
}
head++;
}
}
int main()
{
for(int i=0; i<5; i++)
{
for(int j=0; j<5; j++)
{
scanf("%d",&map1[i][j]);
}
}
memset(visit,0,sizeof(visit));
bfs();
return 0;
}