三、搜索和二分 [Cloned] P - 上一个题的加强版

原题:

A friend of you is doing research on the Traveling Knight Problem (TKP) where you are to find the shortest closed tour of knight moves that visits each square of a given set of n squares on a chessboard exactly once. He thinks that the most difficult part of the problem is determining the smallest number of knight moves between two given squares and that, once you have accomplished this, finding the tour would be easy. 
Of course you know that it is vice versa. So you offer him to write a program that solves the "difficult" part. 

Your job is to write a program that takes two squares a and b as input and then determines the number of knight moves on a shortest route from a to b

题意:

和上一个象棋的题目一样,只不过上一个要求走遍棋盘的每一个格子,这个要求走到一个点,基本一样。

题解:

和上一个一样的深搜。

代码:AC

#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cstring>
#define INF 100000+10
using namespace std;

int dx[8] = {-2,-2,2,2,-1,-1,1,1};
int dy[8] = {1,-1,-1,1,2,-2,-2,2};
int ans = 0,stx,sty,endx,endy;
int board[10][10];
int min(int a,int b)
{
	return a<b?a:b;
}
void dfs(int x,int y,int step)
{
	if(x < 0 || y < 0||x >= 8 ||y >= 8) return;
	if(x == endx&&y == endy)
	{
		ans = min(ans,step);
		return ;
	}
	if(step > 6) return;
	if(step > board[x][y]) return ;
	board[x][y] = step;
	int tx,ty;
	for(int i = 0;i <= 7;i++)
	{
		tx = x+dx[i];
		ty = y+dy[i];
		dfs(tx,ty,step+1);
	}
}
void init()
{  
    int i,j;  
    for(i=0;i<8;++i){  
        for(j=0;j<8;++j){  
            board[i][j] = INF;  
        }  
    }  
}  
int main()
{
	char v[2],n[2]; 
	while(scanf("%s %s",v,n) != EOF)
	{
		ans = INF;
		stx = v[0] - 'a';
		sty = v[1] - '0'-1;
		endx = n[0] - 'a';
		endy = n[1] - '0'-1;
		init();
		dfs(stx,sty,0);
		printf("To get from %s to %s takes %d knight moves.\n",v,n,ans);  
 }
    return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值