首页 > 其他 > 详细

POJ1915

时间:2019-07-19 00:21:55      阅读:75      评论:0      收藏:0      [点我收藏+]

BFS+结构体

在BFS中若有一个点到达了指定位置,就return出函数,用结构体记录每一个点的信息,包括步数,因为最后要输出最小步数。

完整代码

#include <iostream>
#include <cstring>
#include <queue>
using namespace std;
int x2,y2,l;
int vis[310][310];
int k[8][2]={{-1,-2},{-2,-1},{-2,1},{-1,2},{1,-2},{2,-1},{2,1},{1,2}};

struct node
{
    int x,y,s;
    node(int a,int b,int c)
    {
        x=a;
        y=b;
        s=c;    
    }    
};

void bfs(int x,int y)
{
    queue<node> q;
    q.push(node(x,y,0));
    while(!q.empty())
    {
        node t=q.front();
        q.pop();
        if(t.x==x2 && t.y==y2)
        {
            cout<<t.s<<endl;
            return ;
        }
        for(int i=0;i<8;i++)
        {
            int tx=t.x+k[i][0];
            int ty=t.y+k[i][1];
            if(tx>=0 && tx<l && ty>=0 && ty<l && !vis[tx][ty])
            {
                vis[tx][ty]=1;
                q.push(node(tx,ty,t.s+1));
            }
        }
    }
}

int main()
{
    int t,x1,y1;
    cin>>t;
    while(t--)
    {
        memset(vis,0,sizeof(vis));
        cin>>l>>x1>>y1>>x2>>y2;
        bfs(x1,y1);
    }
    return 0;
}

 

POJ1915

原文:https://www.cnblogs.com/benzikun/p/11210500.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!