11494 - Queen

The Problem

The game of Chess has several pieces with curious movements. One of them is the Queen, which can move any number of squares in any direction: in the same line, in the same column or in any of the diagonals, as illustrated by the figure below (black dots represent positions the queen may reach in one move):

The great Chess Master Kary Gasparov invented a new type of chess problem: given the position of a queen in an empty standard chess board (that is, an 8 x 8 board) how many moves are needed so that she reaches another given square in the board?

Kary found the solution for some of those problems, but is having a difficult time to solve some others, and therefore he has asked that you write a program to solve this type of problem.

The Input

The input contains several test cases. The only line of each test case contains four integers X1, Y1, X2 and Y2 (1 ≤ X1, Y1, X2, Y2 ≤ 8). The queen starts in the square with coordinates (X1, Y1), and must finish at the square with coordinates (X2, Y2). In the chessboard, columns are numbered from 1 to 8, from left ro right; lines are also numbered from 1 to 8, from top to bottom. The coordinates of a square in line X and column Y are (X, Y).

The end of input is indicated by a line containing four zeros, separated by spaces.

The Output

For each test case in the input your program must print a single line, containing an integer, indicating the smallest number of moves needed for the queen to reach the new position.

西洋棋中有几个子的走法满特别的,其中一个就是皇后。她可以循垂直、水平、或对角线的方向随她走几格,如下图(黑点表示皇后可以一步走到的格子):


我们的问题是:在标准的西洋棋空棋盘(8 x 8 棋盘) 上摆一个皇后,它要走几步才能走到某个特定的格子?

Input

输入档包含了好几笔测试资料。每笔测试资料只有一行,其中含有整数X1, Y1, X2 及Y2 (1 ≤ X1, Y1, X2, Y2 ≤ 8)。皇后从座标(X1, Y1) 的格子开始,必须在座标(X2, Y2) 的格子结束。在棋盘中的行由左至右编号为1 到8,列则由上至下编号为1 到8。位于第X 列第Y 行的格子其座标为(X, Y)。

输入的结尾以四个由空白隔开的0 来表示。

请参考Sample Input。

Output

对于每笔测试你的程式要印出一行,该行含有一个整数,表示皇后要走到新的位置至少需要几步。

Sample Input

4 4 6 2
3 5 3 5
5 5 4 3
0 0 0 0

Sample Output

1
0
2
解题思路:国际象棋中女王的下法,类似于数学坐标问题,要注意只走1步的条件,横竖直走没有问题,问题是斜着走的条件“(x1-x2)%(y1-y2)==0”
#include<stdio.h>
int main()
{int x1,x2,y1,y2;
while(scanf("%d%d%d%d",&x1,&y1,&x2,&y2)!=EOF){
if((x1==0&&x2==0)&&(y1==0&&y2==0))
break;
if(x1==x2&&y1==y2)
printf("0\n");
else if((y1==y2)||(x1==x2))
printf("1\n");
else if(((x1-x2)/(y1-y2)==-1||(x1-x2)/(y1-y2)==1)&&(x1-x2)%(y1-y2)==0)
printf("1\n");
else printf("2\n");
}
return 0;
}

 

posted on 2013-02-19 18:54  喂喂还债啦  阅读(763)  评论(0编辑  收藏  举报