Moving distance java problem solution

The buildings in the residential community of Planet X are all the same and arranged in a matrix pattern. The number of the building is 1, 2, 3... When a row is full, the number is arranged in the opposite direction from the adjacent building in the next row.
•For example: when the number width of the community is 6, the starting situation is as follows:
•1 2 3 4 5 6
•12 11 10 9 8 7
•13 14 15…
•Our problem is: two building numbers m and n, the shortest moving distance between them (can't move diagonally) is required.
•Input is 3 integers wmn, separated by spaces, all in the range of 1 to 10000.
•w is the width of the row number, m and n are to be calculated The building number.
• It is required to output an integer, which represents the shortest moving distance between the two buildings of mn.

• For example:
• User input:
• 6 8 2
• Then, the program should output:
• 4
• Another example:
• User input:
• 4 7 20
• Then, the program should output:
• 5

It is not allowed to move in a diagonal direction. It is easy to know the walking route between the two points, first left and then right or right and then left, and the distance is the same. So only by determining the coordinates of two points, the distance can be obtained by making the difference between the x and y coordinates.
The only thing that needs to be noticed is that the coordinates are different and pay attention to the positive and negative relationship .

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;
    }
}

Guess you like

Origin blog.csdn.net/m0_48036171/article/details/114235821