POJ 2243-Knight Moves(DFS-跳马)

来源:互联网 发布:驾照报考软件 编辑:程序博客网 时间:2024/06/06 03:10
Knight Moves
Time Limit: 1000MS Memory Limit: 65536KTotal 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 e4a1 b2b2 c3a1 h8a1 h7h8 a1b1 c3f6 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 1000010int 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 e4a1 b2b2 c3a1 h8a1 h7h8 a1b1 c3f6 f6**/

[NOTE]
问:
答:
0 0
原创粉丝点击