poj 3986(bfs)

打印路径的bfs

#include <iostream>
#include <cstring>
#include <algorithm>
#include <cstdio>
#include <map>
#include <queue>
using namespace std;
const int maxn=10;
int a[maxn][maxn];
int dic[10][5]={{1,0},{-1,0},{0,-1},{0,1}};
struct note
{
    int x;
    int y;
    bool operator <(const note &p) const//map具有自动排序功能,要指定优先级
    {
        return x<p.x||(x==p.x)&&(y<p.y);
    }
}aa[50];
map<note,note> mp;
note bfs()
{  a[1][1]=1;
    queue<note> q;
    q.push(note{1,1});
     while(q.size())
     {
          note pp=q.front();
          q.pop();
        for(int i=0;i<4;i++)
        {
            int xx=pp.x+dic[i][0];
            int yy=pp.y+dic[i][1];
         note mmp=mp[note{3,4}];
          if(xx>=1&&xx<=5&&yy>=1&&yy<=5&&a[xx][yy]!=1)
          {
              mp[note{xx,yy}]=note{pp.x,pp.y};//存储路径
if(xx==5&&yy==5) return note{xx,yy}; a[xx][yy]=1; q.push(note{xx,yy}); } } } } void put(note t) { memset(aa,0,sizeof(aa)); int cnt=0; for(note i=t;;i=mp[i]) { aa[cnt++]=i; if(i.x==1&&i.y==1) break; } for(int i=cnt-1;i>=0;i--) printf("(%d, %d)\n",aa[i].x-1,aa[i].y-1); } int main() { while(~scanf("%d",&a[1][1])) { mp.clear(); for(int i=2;i<=5;i++) scanf("%d",&a[1][i]); for(int i=2;i<=5;i++) for(int j=1;j<=5;j++) scanf("%d",&a[i][j]); note nn=bfs(); put(nn); } return 0; }

 

posted on 2017-08-31 11:24  发牌员  阅读(181)  评论(0编辑  收藏  举报

导航