Knight Moves pku 1915

此题为广度优先搜索(BFS)第一次做这种搜索,起先一位用DFS穷举,再排序,汗!一天断断续续的学队列数据结构,搜索,终于A掉了。决定下个月开始看数据结构了,不然很惨。。。

#include<iostream>
#include<string.h>
using namespace std;

struct Queue
{
    int x;
    int y;
    int deep;
};/*队列*/

bool visited[305][305];
Queue queue[100000],temp;/*数组开小导致Runtime error*/
int w[8][2]= {{-1,2},{-1,-2},{1,2},{1,-2},{2,-1},{2,1},{-2,-1},{-2,1}};/*一步可以跳的所有情况*/
 int t,x1,y1,x2,y2,n;

int bfs()
{
    for(int i=0;i<n;i++)
    {
        for(int j=0;j<n;j++)
        {
            visited[i][j]=false;
        }
    }
    queue[0].x=x1;
    queue[0].y=y1;
    queue[0].deep=0;
    visited[x1][y1]=true;
    int start=0,end=1;/*分别表示搜索节点,和队尾加入位置*/
    while(1)
    {
        for(int i=0;i<8;i++)
        {
            temp.x=queue[start].x+w[i][0];
            temp.y=queue[start].y+w[i][1];
            temp.deep=queue[start].deep+1;
            if(temp.x>=0&&temp.x<n&&temp.y>=0&&temp.y<n&&visited[temp.x][temp.y]==false)
            {
                if(temp.x==x2&&temp.y==y2)
                {
                    return temp.deep;
                }
                else
                {
                    queue[end++]=temp;
                    visited[temp.x][temp.y]=true;
                }
            }
        }
        start++;
    }
}

int main()
{
    cin>>t;
    while(t--)
    {
        int count;
        cin>>n>>x1>>y1>>x2>>y2;
        if(x1==x2&&y1==y2)
           cout<<"0"<<endl;
        else
        {
            count=bfs();
            cout<<count<<endl;
        }
    }
    return 0;
}
       
 总结:学习了BFS,要学的还很多很多很多很多很多。。。。。。  

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值