First, the construction of the Serpentine matrix, and output by rows
Cases:
Input: N,
Creating a n*n-serpentine matrix
1 2 3
8 9 4
7 6 5
Output: 1 2 3 8 9 4 7 6 5
Java encoding
Public Static voidMain (string[] args) {//TODO auto-generated Method StubScanner in=NewScanner (system.in); intn =In.nextint (); if(N < 0) return; if(n = = 1) {System.out.println (1); return; } int[] m =New int[N][n]; //define 4 variables to record the upper and lower bounds of the current row and column, respectively intI1 = 0, J1 = 0, i2 = n-1, J2 = n-1; inti = 0, j = 0; intBegin = 1; //4 for loops, traversing the Serpentine matrix while(I1 <= i2 && J1 <=J2) { for(; J <= J2; ++j) {//One rowM[I][J] =begin; Begin++; } J--; I++; I1++; for(; I <= i2; ++i) {//One columnM[I][J] =begin; Begin++; } J2--; J--; I--; for(; J >= J1;--j) {//One rowM[I][J] =begin; Begin++; } i2--; J++; I--; for(; I >= i1; i.) {//One columnM[I][J] =begin; Begin++; } J1++; J++; I++; } //output a serpentine matrix by row for(i = 0; i < n; + +)i) for(j = 0; J < N; + +)j) System.out.println (M[i][j]+ " "); }
Second, known serpentine matrix m, clockwise sequential output
Cases:
Matrix M
1 2 3 4
12 13 14 5
11 16 15 6
10 9 8 7
Output: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
Public Static voidMain (string[] args) {//TODO auto-generated Method Stub int[] m = {{1,2,3,4},{12,13,14,5},{11,16,15,6},{10,9,8,7}}; intn =m.length; intc = m[0].length; if(n = = 1){ for(intA = 0; A < M[0].length; ++a) System.out.print (m[0][a] + ""); } if(c = = 1){ for(intA = 0; A < M.length; ++a) System.out.print (m[a][0] + ""); } //define 4 pointers to record the upper and lower bounds of rows and columns intI1 = 0, J1 = 0, i2 = n-1,j2 = C-1; inti = 0, j = 0; while(I1 <= i2 && j1 <= J2) {//One row for(; J <= J2; + +)j) System.out.print (M[i][j]+ " "); I++; J--; I1++; for(; I <= i2; ++i)//One columnSystem.out.print (M[i][j] + ""); I--; J--; J2--; for(; J >= J1;--j)//One rowSystem.out.print (M[i][j] + ""); I--; J++; I2--; for(; I >= i1; i.)//One columnSystem.out.print (M[i][j] + ""); I++; J++; J1++; } }
Construction and traversal output of Java coded serpentine matrix