The serpentine matrix is a special matrix, but as long as the law of coordinates is, it is not difficult to implement the program.
Here is the serpentine matrix I have implemented by Java:
N = 4
The output is:
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 ("Enter:");
Input = Integer.Parseint (STR);
IF (INPUT> 0 && Input { 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 not legal, must be between 1 ~ 10!"); } }