POJ1915

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;
}

猜你喜欢

转载自www.cnblogs.com/benzikun/p/11210500.html
POJ