题目
917:Knight Moves
总时间限制: 1000ms 内存限制: 65536kB
描述
Background
Mr Somurolov, fabulous chess-gamer indeed, asserts that no one else but him can move knights from one position to another so fast. Can you beat him?
The Problem
Your task is to write a program to calculate the minimum number of moves needed for a knight to reach one point from another, so that you have the chance to be faster than Somurolov.
For people not familiar with chess, the possible knight moves are shown in Figure 1.
输入
The input begins with the number n of scenarios on a single line by itself.
Next follow n scenarios. Each scenario consists of three lines containing integer numbers. The first line specifies the length l of a side of the chess board (4 <= l <= 300). The entire board has size l * l. The second and third line contain pair of integers {0, …, l-1}*{0, …, l-1} specifying the starting and ending position of the knight on the board. The integers are separated by a single blank. You can assume that the positions are valid positions on the chess board of that scenario.
输出
For each scenario of the input you have to calculate the minimal amount of knight moves which are necessary to move from the starting point to the ending point. If starting point and ending point are equal,distance is zero. The distance must be written on a single line.
样例输入
3
8
0 0
7 0
100
0 0
30 50
10
1 1
1 1
样例输出
5
28
0
翻译
题目:移动骑士
背景:
Somurov先生,确实是一位出色的国际象棋棋手,声称除了他之外,没有人能如此迅速地将骑士从一个位置移动到另一个位置。你能打败他吗?
问题:
你的任务是编写一个程序来计算骑士从一个点到另一个点所需的最小移动次数,这样你就有机会比索穆罗洛夫更快。
对于不熟悉国际象棋的人来说,可能的骑士招式如图1所示。
输入:
输入以单行上的场景数n开始。
接下来是n个场景。每个场景由包含整数的三行组成。第一行指定棋盘一侧的长度l(4<=l<=300)。整个棋盘的大小为ll。
第二行和第三行包含一对整数{0,…,l-1}{0,…,l-1},指定骑士在棋盘上的起始和结束位置。整数由一个空格分隔。
您可以假设这些位置是该场景棋盘上的有效位置。
输出:
对于输入的每个场景,您必须计算从起点移动到终点所需的骑士移动的最小数量。如果起点和终点相等,则距离为零。距离必须写在一行上。
理解
1.出发点到目的地的最短距离。用宽搜撒一次就搞定
2.深搜就得回溯尝试所有的线路。
代码
#include <bits/stdc++.h>
//#include <windows.h>
using namespace std;
struct point{
int x,y,t;
}o,p[310][310];
int n,w,
sx,sy,
ex,ey,
d[8][2]={{-1,-2},{-2,-1},{-2,1},{-1,2},{1,2},{2,1},{2,-1},{1,-2}};
void view(){
cout<<“地图”<<endl;
cout<<“列:\t”;for(int j=1;j<=w;j++)cout<<j<<“\t”;cout<<endl;
for(int i=1;i<=w;i++){
cout<<i<<“行\t”;
for(int j=1;j<=w;j++)cout<<p[i][j].t<<“\t”;
cout<<endl;
}
//Sleep(2000);
}
int main(){
//freopen(“data.cpp”,“r”,stdin);
cin>>n;
while(n–){
queue q;
cin>>w>>sx>>sy>>ex>>ey;
for(int i=1;i<=w;i++)
for(int j=1;j<=w;j++)p[i][j]=point{i,j,0};
//view();
p[sx+1][sy+1].t=1;
q.push(point{sx+1,sy+1,0});
int x,y;
while(!q.empty()){
o=q.front();q.pop();
//cout<<“出发:”<<o.x<<“,”<<o.y<<“=”<<o.t<<endl;
if(o.xex+1&&o.yey+1){
cout<<o.t<<endl;break;
}
for(int i=0;i<8;i++){
x=o.x+d[i][0],y=o.y+d[i][1];
if(x<1||x>w||y<1||y>w||p[x][y].t)continue;
p[x][y].t=o.t+1;
//cout<<“到达:”<<x<<“,”<<y<<“=”<<p[x][y].t<<endl;
q.push(p[x][y]);
}
//view();
}
}
return 0;
}