Title: Enter a matrix that prints each number in a clockwise order from the outside, for example, if you enter the following 4 X 4 matrix: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 Print the numbers in sequence 1,2,3,4,8,12,16,15,14,1 3,9,5,6,7,11,10.
Analysis: There are a lot of variables in the book, not to understand, here with an auxiliary array, used to determine the node has been visited.
PackageCom.gjjun.jzoffer;Importjava.util.ArrayList;Importjava.util.Arrays;Importjava.util.List;/*** Print Matrix clockwise * *@authorGjjun * @date 2018/8/21 **/ Public classSolution29 { Public Static voidMain (string[] args) {int[] arr =New int[2] [4]; intnum = 1; for(inti = 0; I < 2; i++) { for(intj = 0; J < 4; J + +) {Arr[i][j]=num; Num++; }} System.out.println (Arrays.deeptostring (arr)); System.out.println (arrays.tostring (Print (arr). ToArray ())); } Public Staticarraylist<integer> Print (int[] Array) {ArrayList<Integer> list =NewArraylist<>(); if(Array = =NULL|| Array.Length = = 0) { returnlist; } introw =Array.Length; intCol = array[0].length; int[] temp =New int[Row][col]; temp[0][0] = 1; inti = 0; intj = 0; List.add (Array[i][j]); intmin = row > col?Col:row; Min= (min & 1) = = 1? MIN/2 + 1:MIN/2; while(min--> 0) { while(J < Col-1 && temp[i][j + 1] = = 0) {List.add (array[i][j+ 1]); Temp[i][j+ 1] = 1; J++; } while(I < row-1 && temp[i + 1][j] = = 0) {List.add (array[i+ 1][j]); Temp[i+ 1][j] = 1; I++; } while(J > 0 && temp[i][j-1] = = 0) {List.add (array[i][j-1]); Temp[i][j-1] = 1; J--; } while(i > 0 && temp[i-1][j] = = 0) {List.add (array[i-1][j]); Temp[i-1][J] = 1; I--; } } returnlist; }}
The sword refers to an offer (book): Print an array clockwise