It is said that it is a written question of Netease youdao (implemented in Java)

Source: Internet
Author: User

1. Print the following matrix;

N = 5:

1 2 9 10 25

4 3 8 11 24

5 6 7 12 23

16 15 14 13 22

17 18 19 20 21

N = 6:

1 2 9 10 25 26

4 3 8 11 24 27

5 6 7 12 23 28

16 15 14 13 22 29

17 18 19 20 21 30

36 35 34 33 32 31

 

 

 

Code:

Public class printrect {
Private int [] [] array;
Private int N;

Public printrect (int n ){
This. n = N;
Array = new int [N] [N];
}

Public void Init (){
Array [0] [0] = 1;
For (INT I = 2; I <= N; I ++ ){
Int start = (I-1) * (I-1) + 1;
If (I % 2 = 0 ){
For (Int J = 0; j <I; j ++ ){
Array [J] [I-1] = start;
Start ++;
}
For (Int J = I-2; j> = 0; j --){
Array [I-1] [J] = start;
Start ++;
}
} Else {
For (Int J = 0; j <I; j ++ ){
Array [I-1] [J] = start;
Start ++;
}
For (Int J = I-2; j> = 0; j --){
Array [J] [I-1] = start;
Start ++;
}
}
}
}

Public void print (){
For (INT I = 0; I <n; I ++ ){
For (Int J = 0; j <n; j ++ ){
System. Out. Print (array [I] [J] + "\ t ");
}
System. Out. println ();
}
}

Public static void main (string [] ARGs ){
Printrect Pr = new printrect (6 );
Pr. INIT ();
Pr. Print ();

}

}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.