Code of the snake Matrix

Source: Internet
Author: User
The snake matrix is a special matrix, but it is not difficult to use a program to implement it as long as you have mastered the laws of coordinates.
The following is the snake Matrix I implemented using Java:
When N = 4
Output:
1 2 6 7
3 5 8 13
4 9 12 14
10 11 15 16

The source code is implemented as follows:

Import javax. Swing. joptionpane;
Public class test
{
Public static void main (string [] ARGs)
{
String STR;
Final int max = 10;
Int input;
Int D, I, j, M;
Int A [] [] = new int [10] [10];
STR = joptionpane. showinputdialog ("input :");
Input = integer. parseint (STR );
If (input> 0 & input <max)
{
I = 1;
J = 1;
M = 1;
D = 1;
Do
{
A [J] = m;
Switch (d)
{
Case 1: J ++; if (I = 1) d = 2; else d = 4; break;
Case 2: I ++; j --; if (I = input) d = 1;
Else if (j = 1) d = 3; break;
Case 3: I ++; If (j = input) d = 2; else d = 4; break;

Case 4: J ++; I --; If (j = input) d = 3; else if (I = 1) d = 1; break;

}
M ++;
} While (M <= input * input );
System. Out. println ("output :");
System. Out. println ();
For (I = 1; I <= input; I ++)
{
For (j = 1; j <= input; j ++)
{System. Out. Print ("" + A [J]);}
System. Out. println ();
}
}
Else
System. Out. println ("the number of inputs is invalid. It must be 1 ~ Between 10! ");

}

}

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.