移动距离
X星球居民小区的楼房全是一样的,并且按矩阵样式排列。其楼房的编号为1,2,3…
当排满一行时,从下一行相邻的楼往反方向排号。
比如:当小区排号宽度为6时,开始情形如下:
1 2 3 4 5 6
12 11 10 9 8 7
13 14 15 …
我们的问题是:已知了两个楼号m和n,需要求出它们之间的最短移动距离(不能斜线方向移动)
输入为3个整数w m n,空格分开,都在1到10000范围内
w为排号宽度,m,n为待计算的楼号。
要求输出一个整数,表示m n 两楼间最短移动距离。
例如:
用户输入:
6 8 2
则,程序应该输出:
4
再例如:
用户输入:
4 7 20
则,程序应该输出:
5
public class Main {
static int result = 0;
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int w = sc.nextInt();
int h1 = sc.nextInt();
int h2 = sc.nextInt();
result += Math.abs(hang(h1, w) - hang(h2, w));
result += Math.abs(length(h1, w) - length(h2, w));
System.out.print(result);
}
public static int hang(int h, int k) { //判断行数
if(h % k == 0 ) return h/k;
else return h/k+1;
}
public static int length(int h, int k) { //判断每个数距离每一行左边第一个数的距离
if(hang(h, k) % 2 == 0 ) return hang(h, k)*k-h;
else return h-1-(hang(h, k)-1)*k;
}
}
题目很好懂,要注意判断奇偶行和其他的。