http://poj.org/problem?id=3984
看world final 的同时水了一发bfs,就是要记录路径。。
记录路径还是不太熟呀。。
上代码:
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <queue>
#include <stack>
using namespace std;
#define M 10
int d1[4] = {0,0,1,-1};
int d2[4] = {1,-1,0,0};
int mp[10][10];
int vis[10][10];
struct state
{
int x,y;
int time;
int lx,ly;
}next1,cur,ls[10][10]; //ls记录路径数组
stack<state> s;
void bfs(state temp)
{
vis[temp.x][temp.y] = 1;
queue<state> q;
q.push(temp);
while(!q.empty())
{
cur = q.front();
q.pop();
if(cur.x==4 && cur.y==4)
{
s.push(cur);
while(1)
{
state tt;
tt.x = ls[cur.x][cur.y].lx;
tt.y = ls[cur.x][cur.y].ly;
s.push(tt);
cur = tt;
if(cur.x==0 && cur.y==0) return;
}
}
for(int i = 0;i < 4;i++)
{
next1.x = cur.x+d1[i];
next1.y = cur.y+d2[i];
if(next1.x>=0 && next1.x<5 && next1.y>=0 && next1.y<5 && !vis[next1.x][next1.y] && mp[next1.x][next1.y]==0)
{
ls[next1.x][next1.y].lx = cur.x; //记录上一个的位置
ls[next1.x][next1.y].ly = cur.y;
vis[next1.x][next1.y] = 1;
q.push(next1);
}
}
}
}
int main()
{
//while(1)
{
while(!s.empty()) s.pop();
for(int i = 0; i < 5;i++)
{
for(int j = 0;j < 5;j++)
{
scanf("%d",&mp[i][j]);
}
}
cur.x = 0;
cur.y = 0;
cur.time = 0;
cur.lx = -1;
cur.ly = -1;
bfs(cur);
while(!s.empty())
{
state temp = s.top();
s.pop();
printf("(%d, %d)\n",temp.x,temp.y);
}
}
return 0;
}