bfs(hdu1372)

思路:8个方向依次入队即可,只需标记访问,广度优先搜索是按照层次来搜索,如果存在一条通路,那么自然是最短路了。

ac代码:

#include<iostream>  
#include<cstring>  
#include<string>  
#include<queue>  
#include <fstream>  
using namespace std;  
struct node{  
    int x,y;  
    int step;  
}p,q;  
queue<node> Q;  
int dir[8][2]={-2,-1,-2,1,-1,-2,-1,2,1,-2,1,2,2,-1,2,1};  
int sx,sy,endx,endy;  
bool visit[10][10];  
bool isbond(node &a){  
    if(a.x<0 || a.x>7 || a.y<0 || a.y>7)return 1;  
    return 0;  
}  
int bfs(){  
    memset(visit,0,sizeof(visit));  
    while(!Q.empty())Q.pop();  
    p.step=0;  
    visit[p.x][p.y]=1;  
    Q.push(p);  
    if(p.x==endx&&p.y==endy){  
        return 0;  
    }  
    while(!Q.empty())  
    {  
        p=Q.front();  
        Q.pop();  
        if(p.x==endx&&p.y==endy)return p.step;  
        for(int i=0;i<8;i++)  
        {  
            q.x=p.x+dir[i][0];  
            q.y=p.y+dir[i][1];  
              
            if(isbond(q))continue;  
            if(visit[q.x][q.y])continue;  
              
            q.step=p.step+1;  
            visit[q.x][q.y]=1;  
            Q.push(q);  
              
        }  
    }  
}  
int main()  
{  
    string a,b;  
//  ifstream fin;  
//  fin.open("aaa.txt");  
    while(cin>>a>>b)  
    {  
        p.x=a[0]-'a';  
        p.y=a[1]-'1';  
        endx=b[0]-'a';  
        endy=b[1]-'1';  
        cout<<"To get from "<<a<<" to "<<b<<" takes ";  
        cout<<bfs()<<" knight moves."<<endl;  
    }  
    return 0;  
}  


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值