topic:
An input matrix, each according to a number from the outside in order to print out sequentially clockwise
Ideas:
The print circle divided into four steps: The first step in printing a line from left to right, top to bottom print one line second step, third step is to print a line from right to left, the fourth step from the bottom line is printed, each The step start coordinate and end coordinate can be printed out by a line or a loop.
There may degenerate into the last lap only one line, and only one, or even only a number, such as print circle no longer needs four steps.
Analyze the prerequisites for each step of printing. The first step is always necessary to print around at least one step. If only one line, then it is not the second step.
The second step is to print a prerequisite for termination line number> starting line number
A third step of printing the proviso that terminating line number> starting line number && termination column number> starting column number
Termination condition is the termination of the fourth step the printing line number than the starting row number is at least 2, while the termination column number> starting column number
Code:
public class Seventeenth { public static void printMatrix ( int [] [] Numbers) { IF (Numbers == null ) { return ; } // rows start int X = 0 ; // record start column int Y = 0 ; // the line number is the largest (numbers.length -. 1) / 2 // column number is the largest (numbers [0] .length -1) / 2 the while (* 2 X <Y numbers.length && * 2 <numbers [0 ] .length) { printMatrixInCircle (Numbers, X, Y); X ++ ; Y ++ ; } } public static void printMatrixInCircle ( int [] [] Numbers, int X, int Y) { int rows = numbers.length; int cols = Numbers [0 ] .length; // output the top row for ( int I = Y; I <cols = - Y -. 1; I ++ ) { System.out.println (Numbers [X] [I] + "" ); } // output rightmost column of the loop height of at least 2 // rows - X -1 represents the row number of the lowermost ring that row IF (rows - X -. 1>X) { for ( int I = X +. 1; I <= rows - X -. 1; I ++ ) { System.out.println (Numbers [I] [cols - Y -1] + "" ); } } // loop height and width of the ring is at least 2, at least until the output is below the line 2 // cols -. 1 - Y denotes a column number of the ring and the rightmost column IF (rows - X -. 1> X && cols - . 1 - Y> Y) { for ( int I = cols - Y - 2; I> = Y; I - ) { System.out.println (Numbers [rows -. 1 - X] [I] + "" ); } } // width of the ring height of the ring is at least 2 and 3 will be at least that output leftmost column //the line number of the line 1 represents a ring of the lowermost rows - - X IF (cols - 1 - Y> Y && rows - 1 - X> X + 1 ) { // the left of the row in the first and last has been output for ( int I = rows -. 1 - X -. 1; I> = X +. 1; I - ) { System.out.println (Numbers [I] [Y] + "" ); } } } public static void main (String [] args) { int [] [] ARR = { { l, 2,3 }, { 4,5,6 }, { 7,8,9 } }; printMatrix (ARR); } }