Chat with friends on Friday talk about a serpentine array of Java implementations, the proposition is: Suppose a two-dimensional array width W high h, starting from 1 serpentine output .
int[][] Numbermatric = new Int[w][h];
At that time nap past mind bag is not clear, Leng no good ideas. Later in the evening study, found a relatively simple way to achieve. The core ideas are:
To find the direction of movement, the two-dimensional array is filled in ascending order of movement.
A relatively simple implementation is as follows:
Private voidSnakematric (intWinth) { intx, y;//x, y coordinates. int[] Numbermatric =New int[W][h]; intnum = numbermatric[x = 0][y = 0] = 1; while(Num < w*h) { //Move Right while(Y+1 < w && numbermatric[x][y+1] = = 0/ * When an array of items is not populated,its default value is 0*/) {y++; Numbermatric[x][y]= ++num; } //Move Down while(x+1) {x++; Numbermatric[x][y]= ++num; } //Move left while(y-1>=0 && numbermatric[x][y-1] = = 0) {y--; Numbermatric[x][y]= ++num; } //Move Upward while(x-1>=0 && numbermatric[x-1][y] = = 0) {x--; Numbermatric[x][y]= ++num; } } //Print Output for(x = 0;x < w;x++){ for(y = 0;y < h;y++) {System.out.printf ("%4d", Numbermatric[x][y]); } System.out.println ();//line Break } }
Simple implementation code for the Java Serpentine array