经典指数          
原因
2238
浏览数
0
收藏数
 

国际象棋的棋盘是黑白相间的8x8的方格,棋子放在格子中间。王、后、车、象的走子规则如下: * 王:横、直、斜都可以走,但每步限走一格。 * 后:横、直、斜都可以走,每步格数不受限制。 * 车:横、竖均可以走,不能斜走,格数不限。 * 象:只能斜走,格数不限。 写一个程序,给定起始位置和目标位置,计算王、后、车、象从起始位置走到目标位置所需的最少步数。 输入描述: 输入包含多组数据,每组数据包含棋盘上的两个位置,第一个是起始位置,第二个是目标位置。两个位置不相同。位置用"字母+数字"的形式表示,字母从“a”到“h”代表列号,数字从“1”到“8”,代表行号。例如“a1”就是第一行第一列、“f5”就是第五行第六行。 输出描述: 对应每一组数据,输出王、后、车、象所需的最少步数,中间用一个空格隔开。如果无法到达,就输出“Inf”。 输入例子: a1 c3f5 f8 输出例子: 2 1 2 13 1 1 Inf

     举报   纠错  
 
切换
1 个答案

package newcoder_test;

import java.io.BufferedReader;

import java.io.IOException;

import java.io.InputStreamReader;

import java.util.ArrayList;

import java.util.List;

public class Chess {

public static void main(String[] args) throws IOException {

BufferedReader bufr = new BufferedReader(new InputStreamReader(

System.in));

String line = null;

List list = new ArrayList();

while (!"".equals((line = bufr.readLine()))) {

list.add(line);

}

for (String str : list) {

String[] strArr = str.split(" ");

char[] start = strArr[0].toCharArray();// 起点 {a,1}

char[] end = strArr[1].toCharArray();// 终点 {c,3}

move(start, end);

}

}

private static void move(char[] start, char[] end) {

int width = Math.abs(start[0] - end[0]);// 横向距离

int height = Math.abs(start[1] - end[1]);// 纵向距离

/*

* 王

*/

System.out.print(Math.max(width, height) + " ");

/*

* 后

*/

if (width == 0 || height == 0 || width == height)

System.out.print(1 + " ");

else

System.out.print(2 + " ");

/*

* 车

*/

if (width == 0 || height == 0)

System.out.print(1 + " ");

else

System.out.print(2 + " ");

/*

* 象

*/

if (width != height)

System.out.print("Inf");

else

System.out.print(width);

}

}

 
切换
撰写答案