hdu1372 Knight Moves(BFS)

来源:互联网 发布:ins是什么社交软件 编辑:程序博客网 时间:2024/05/21 06:55

       搜索题也做了一些了,发现这一题又回到最初始的问题。这一题的话,就是简单的按8个方向进行搜索(因为马可以有8个落点)。下面就直接贴代码了

(本题题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1372)

(其实hdu2717 和这一题也是十分相似的:http://acm.hdu.edu.cn/showproblem.php?pid=2717)

代码+注释:

#include <iostream>#include <stdio.h>#include <string.h>#include <queue>using namespace std;typedef struct{    int x,y;}coordinate;queue<coordinate>Q;coordinate start,goal;//start为起始位置,goal为目标位置int chessboard[8][8];const int dx[8]={-2,-1,1,2,2,1,-1,-2},          dy[8]={1,2,2,1,-1,-2,-2,-1};//位移参量bool Inborder(int x,int y){    //控制边界,防止越界    if(x<0||x>7||y<0||y>7)        return false;    return true;}int BFS(){    coordinate now,next;    while(!Q.empty())  //队列初始化        Q.pop();    Q.push(start);    //将起点加入队列    chessboard[start.x][start.y]=1;    //将起始位置进行标记    while(!Q.empty()){        now=Q.front();        Q.pop();        if(now.x==goal.x&&now.y==goal.y) break;        //若当前状态达到目标位置则结束搜索        for(int i=0;i<8;i++){            next.x=now.x+dx[i];            next.y=now.y+dy[i];            //进行8个方向遍历            if(chessboard[next.x][next.y]==0&&Inborder(next.x,next.y)){                //判断是否访问过该位置,且在棋盘内                chessboard[next.x][next.y]=chessboard[now.x][now.y]+1;                //若可以访问的话步数+1                Q.push(next);                //将当前状态加入队列            }        }    }    return chessboard[goal.x][goal.y]-1;}int main(){    char c1,c2;    int t1,t2;    while(cin>>c1>>t1>>c2>>t2){        start.x=c1-'a',start.y=t1-1;        goal.x =c2-'a',goal.y =t2-1;        memset(chessboard,0,sizeof(chessboard));        printf("To get from %c%d to %c%d takes %d knight moves.\n",               start.x+'a',start.y+1,goal.x+'a',goal.y+1,BFS());    }    return 0;}


 

1 0
原创粉丝点击