【问题描述】:
x星球居民小区楼房全是一样的,并且按照矩阵样式排列。其楼房编号为:1,2,3,4,5…当排满一行时,从下一行相邻的楼往反方向排号。
比如小区排号宽度为6时,开始情形如下:
1 2 3 4 5 6
12 11 10 9 8 7
13 14 15 16 …
【问题】:
已知俩楼号m和n,需要求出他们之间最短移动距离(不能斜线方向移动)。
输入三个整数:w m n,空格分开,且 1<=w,m,n<=10000;要求输出一个整数,表示m与n之间的最短移动距离。
【样例输入】:
6 8 2
【样例输出】:
4
【样例输入】:
4 7 20
【样例输出】:
5
import java.util.Scanner;
public class XStar {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
//输入 w m n
int w = scanner.nextInt();
int m = scanner.nextInt();
int n = scanner.nextInt();
//求出 m m 中 max 与 min
int max = Math.max(m, n);
int min = Math.min(m, n);
int num = 0 ;
int x = 0,y = 0;
//算出最大行
int line = 0;
if(max % w == 0) {
line+=max/w;
}else {
line+= max / w + 1;
}
//定义 line行 w列的数组
int [][]arr = new int[line][w];
int temp = 1;
outer:
for (int i = 0; i < arr.length; i++) {
if (i % 2 == 0) {
for (int j = 0; j < arr[i].length; j++) {
//如果temp等于 min 记录 x y
if(temp == min) {
x = x+i;
y = y+j;
}
//如果temp等于max 计算路径
if(temp == max) {
num =Math.abs(i-x) + Math.abs(j-y);
break outer;
}
arr[i][j] = temp;
temp ++;
}
}else {
for (int j = arr[i].length-1; j >=0; j--) {
if(temp == min) {
x = x+i;
y = y+j;
}
if(temp == max) {
num =Math.abs(i-x) + Math.abs(j-y);
}
arr[i][j] = temp;
temp ++;
}
}
}
System.out.println(num);
}
}