移动距离java题解

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

不能斜线方向移动,通过题意易知两点间,先左后右或者先右后左的行走路线,距离一致。所以只需要通过确定两点坐标,在通过x,y坐标作差就可以得到距离。
需要注意的只是坐标作差注意正负关系即可。

import java.util.Scanner;
public class T2778 {
    
    
    public static void main(String[] args) {
    
    
        int w,m,n;
        Scanner sc = new Scanner(System.in);
        w = sc.nextInt();
        m = sc.nextInt();
        n = sc.nextInt();
        int distance = Math.abs((Locate(w,m)[1]-Locate(w,n)[1]))+Math.abs((Locate(w,m)[0]-Locate(w,n)[0]));
        System.out.println(distance);
    }

    public static int[] Locate(int w,int m){
    
    
        int[] location = new int[2];
        int x1 = 1,y1 = 1;
        if (m % w == 0)
            y1 = m / w;
        else
            y1 = (m/w)+1;

        if (y1 % 2 == 0){
    
    
            if (m % w == 0)
                x1 = 1;
            else
                x1 = 1 + (w - m % w);
        }
        else if (y1 % 2 ==1){
    
    
            if (m % w == 0)
                x1 = w;
            else
                x1 = m % w;
        }
        location[0] = x1;
        location[1] = y1;
        return location;
    }
}

猜你喜欢

转载自blog.csdn.net/m0_48036171/article/details/114235821