UVA 439 Knight Moves

UVA 439 Knight Moves

题目

中文简单翻译就是国际象棋规定马的起点终点,算出最短路径。

分析

就是简单的广度优先遍历BFS,用队列,格式如下

queue.push(root)
while(!queue)
{
    var buf = queue.front();
    //处理这个节点
    for(...)
    {

        queue.push();   
    }
    queue.pop();
}

代码

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

int movex[8]={-2,-2,-1,-1,1,1,2,2};
int movey[8]={-1,1,2,-2,-2,2,1,-1};
int map[9][9];


class point
{
    public :
        int x;
        int y;
        int count = 0;  
};
int bfs(point ,point);
int main()
{
    char x1,x2,y1,y2;
    while (cin>>x1>>y1>>x2>>y2)
    {
        point start ;
        point end ;
        start.x=x1-'a'+1;
        start.y=y1-'0';
        end.x=x2-'a'+1;
        end.y=y2-'0';
        printf("To get from %c%c to %c%c takes %d knight moves.\n",x1,y1,x2,y2,bfs(start,end));
    }
}
int bfs(point start,point end)
{
    if(start.x==end.x&&start.y==end.y) return 0;
    queue<point> q;
    q.push(start);
    while(!q.empty())
    {
        point buf_q=q.front();
        for(int i=0;i<8;i++){
            int x=buf_q.x+movex[i];
            int y=buf_q.y+movey[i];
            if(x>0&&x<9&&y>0&&y<9)
            {
                if(x==end.x&&y==end.y)return buf_q.count+1;
                else{
                    point input;
                    input.x=x;
                    input.y=y;
                    input.count=buf_q.count+1;
                    q.push(input);
                }
            }
        }
        q.pop();
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值