XStar房屋最短路径

【问题描述】:
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);
		
	}
	
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值