您的位置:首页 > 其它

POJ 2243-Knight Moves(DFS-跳马)

2016-07-29 16:00 483 查看
Knight Moves

Time Limit: 1000MS Memory Limit: 65536K
Total Submissions: 13444 Accepted: 7525
Description

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.
Input

The input will contain one or more test cases. Each test case consists of one line containing two squares separated by one space. A square is a string consisting of a letter (a-h) representing the column and a digit (1-8) representing the row on the chessboard.
Output

For each test case, print one line saying "To get from xx to yy takes n knight moves.".
Sample Input
e2 e4
a1 b2
b2 c3
a1 h8
a1 h7
h8 a1
b1 c3
f6 f6

Sample 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.

Source

Ulm Local 

题目意思:

给定棋盘上两个位置,计算马从a到b所需的最小步骤。

解题思路:

DFS。

#include<cstdio>
#include<cstring>
#include<cmath>
#include<set>
#include<cstdlib>
#include<iostream>
#include<algorithm>
using namespace std;
#define MAXN 1000010
int vis[8][8],step[8][8];//map[8][8];
int dir[8][2]= {{-2,-1},{-2,1},{-1,-2},{-1,2},{2,-1},{2,1},{1,-2},{1,2}};
int res=0,st,ans;
int sx,sy,ex,ey;
void dfs(int x,int y,int st)
{
if(x<0||y<0||x>=8||y>=8||st>=ans)
return;
int i,j,tx,ty;
if(x==ex&&y==ey)//能经过每个点且仅一次
{
ans=min(st,ans);
//cout<<"ans="<<ans<<" st="<<st<<endl;
return ;
}
if(!vis[x][y])
{
vis[x][y]=1;
step[x][y]=st;
}
else
{
if(step[x][y]<=st)
return;
step[x][y]=st;
}
for(i=0; i<8; ++i)
{
tx=x+dir[i][0];
ty=y+dir[i][1];
dfs(tx,ty,st+1);
}
}
int main()
{
ios::sync_with_stdio(false);
cin.tie(0);
char x1,y1;
while(cin>>x1>>sx>>y1>>ex)
{
--sx,--ex;
sy=int(x1)-'a',ey=int(y1)-'a';
int i,j;
memset(vis,0,sizeof(vis));
st=0;
ans=MAXN;
dfs(sx,sy,0);
cout<<"To get from "<<x1<<++sx<<" to "<<y1<<++ex<<" takes "<<ans<<" knight moves."<<endl;
}
return 0;
}
/**
e2 e4 a1 b2 b2 c3 a1 h8 a1 h7 h8 a1 b1 c3 f6 f6**/


[NOTE]

问:



答:



内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  POJ 2243 Knight Moves DFS