uva 439 Knight Moves(马移动) —— DFS + 剪枝

/**
序号:num_6
作者:MrZhang
日期:2016-5-24


题目名称: Knight Moves(马移动)
题目来源:
uva —— 439 —— Knight Moves
网址:
英文题目:http://acm.hust.edu.cn/vjudge/problem/viewProblem.action?id=19436
--------------------------------------
数据样例:
input:

e2 e4
a1 b2
b2 c3
a1 h8
a1 h7
h8 a1
b1 c3
f6 f6

output

To get from e2 to e4 takes 2 knight moves.
To get from a1 to b2 takes 4 knight moves.
To get from b2 to c3 takes 2 knight moves.
To get from a1 to h8 takes 6 knight moves.
To get from a1 to h7 takes 5 knight moves.
To get from h8 to a1 takes 6 knight moves.
To get from b1 to c3 takes 1 knight moves.
To get from f6 to f6 takes 0 knight moves.
*/
#include <iostream>
#include <cstring>
#include <cstdio>

using namespace std;
int start_x,start_y;
int aim_x,aim_y;

int INF = 10;
int minLength;
int nowLength;

bool check(int u,int v){
    if(u >= 0 && u <= 7 && v >= 0 && v <= 7) {
        return true;
    }

    return false;
}
//!自上至下第i行
//!           1       2      3     4
int dx[10]={-2,-2,  -1,-1,  1,1,  2,2};
int dy[10]={-1, 1,  -2, 2, -2,2, -1,1};

void dfs(int x,int y){
    if(x == aim_x && y == aim_y){
        if(nowLength < minLength)
        {
            minLength = nowLength;
            return ;
        }


    }

    for(int i=0;i<8;i++){
        int u = x + dx[i], v = y +dy[i];

        if(check(u,v) && nowLength < minLength){
            nowLength ++;
            dfs(u,v);
            nowLength --;
        }
    }

}

int main(){
    char input[10];
    while(gets(input)){
        minLength = INF;
        nowLength = 0;

        start_x = input[0] - 'a';
        start_y = input[1] - '1';

        aim_x = input[3] - 'a';
        aim_y = input[4] - '1';

        dfs(start_x,start_y);

        cout<<"To get from "<<input[0]<<input[1]<<" to "<<input[3]<<input[4]<<" takes "<<minLength<<" knight moves."<<endl;
    }

    return 0;
}
/**

总结:

题型:图的遍历

原理:DFS +剪枝

针对此题目的理解:
1.马有8种走法
2.下一个点是否符合规定
(1)只有 没出界。———— u >= 0 && u <= 7 && v >= 0 && v <= 7
(2)有没有必要遍历?
若nowLength > minLength,就没有必要再遍历了。(此即所谓的剪枝)
*/

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

张之海

若有帮助,客官打赏一分吧

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值