day13 754 square matrix II (find the law)

754. Square Matrix II

Input integer NNN , output aNNA two-dimensional array of order N.

Refer to the example for the format of the array.

Input format The
input contains multiple lines, each line contains an integer NNN

When the input behavior N=0 N=0N=When 0 , it means that the input is over, and the line does not need to be processed.

Output format
For each input integer NNN , output aNNthat meets the requirementsN- order two-dimensional array.

Each array accounts for NNN lines, each line containsNNN integers separated by spaces.

After each array is output, a blank line is output.

Data range
0 ≤ N ≤ 100 0 ≤ N ≤ 1000N. 1 0 0
Input Sample:

1
2
3
4
5
0

Sample output:

1

1 2
2 1

1 2 3
2 1 2
3 2 1

1 2 3 4
2 1 2 3
3 2 1 2
4 3 2 1

1 2 3 4 5
2 1 2 3 4
3 2 1 2 3
4 3 2 1 2
5 4 3 2 1

Ideas:

This question is mainly to find the law. Of course, there are many solutions to this question. The key depends on the law you are thinking of. Here is an intuitive rule that I thought of.

  1. The elements in the symmetrical position are the same.
  2. The ifirst ielement of the first row 1starts from the beginning and then increments. (Here the subscript starts from 0)

Java code

import java.util.Scanner;

public class Main {
    
    
    public static void main(String[] args) {
    
    
        Scanner scanner = new Scanner(System.in);
        int n = scanner.nextInt();
        //当输入0时退出
        while(n != 0){
    
    
            int[][] arr = new int[n][n];//用于存要输出的结果
            int num = 1;
            for(int i = 0;i < n; i++){
    
    
                for(int j = i;j < n;j++){
    
    //注意j是从i位置开始的
                    arr[i][j] = arr[j][i] = num;//对称位置元素相同
                    num++;
                }
                num = 1;//新的一行,num重置为1
            }

            for(int i = 0;i < n; i++){
    
    
                for(int j = 0;j < n;j++){
    
    
                    System.out.print(arr[i][j] + " ");
                }
                System.out.println();
            }
            System.out.println();

            n = scanner.nextInt();//读取下一个n
        }
    }
}

Insert picture description here

Guess you like

Origin blog.csdn.net/YouMing_Li/article/details/113862562