Diagonal printing

Did not do it yesterday written diagonally print, mentality collapse, and do it again today 
/ ** 
 * @author Eightn0 
 * @Create 2021-03-17 19:03 
 * Function: print diagonally aligned array of m * n 
 * / 
public class PrintNums { 
    public static void main(String[] args) { 
        //Prompt to enter an m*n array 
        System.out.println("This program is used to print the array diagonally, please enter the length of the array:"); 
        Scanner scanner = new Scanner(System.in); 
        int m = scanner.nextInt(); 
        System.out.println("Please enter the height of the array:"); 
        int n = scanner.nextInt(); 

        //Generate a two-dimensional array [m][n], store the input data 
        System.out.println("Please input array elements:"); 
        int[][] arr = new int[m][n]; 
        for (int i = 0; i <arr.length; i++) {
            for (int j = 0; j <arr[i].length; j++) { 
                arr[i][j] = scanner.nextInt(); 
            } 
        } 

        //Generate a one-dimensional array to save the result 
        int[] resultArr = new int[m * n]; 

        //Observe the output law, when the subscript and the number are even, move the column +1 to the right when it reaches the first row. If it reaches the last column, add 1 to the row and move it down. 
        //When the subscript sum is odd: If the first column is reached, the row will be incremented by 1 to move down, and if the last row is reached, the column will be incremented by 1 and move to the right. 

        int r = 0; 
        int c = 0; 

        for (int i = 0; i <resultArr.length; i++) { 
            resultArr[i] = arr[r][c]; 
            if ((r + c)% 2 == 0) { 
                if (c == (n-1)) {//The element is in the last column (the last column must be judged first) 
                    r++;//Go down 
                } else if (r == 0) {//The element is in the first OK, go right 
                    c++;
                } else {//Other situations 
                    r--; 
                    c++;
                } 

            } else {//The index sum is odd 
                if (r == (m-1)) {//Last line 
                    c++;//Go right 
                } else if (c == 0) {//First column 
                    r++; //Go down 
                } else { 
                    r++;//line 
                    c--;//column 
                } 
            } 
        } 

        //output result 
        for (Integer integer: resultArr) { 
            System.out.println(integer); 
        } 
    } 
}

Guess you like

Origin blog.csdn.net/vivian233/article/details/114990054