Spiral Matrix II
Given an integer n, generate a square matrix filled with elements from 1 to n2 in Spiral order.
For example,
Given N = 3 ,
You should return the following matrix:
[[1, 2, 3], [8, 9, 4], [7, 6, 5]]
This problem then the above problem, is a reverse process, as long as a slight change, because the above a spiral traversal of the entire array, as long as the traversal process will fill in the number of a good
1 Importjava.util.ArrayList;2 Importjava.util.Arrays;3 Importjava.util.List;4 5 6 7 Public classSolution {8 //list<integer> result = new arraylist<integer> ();9 intresult[][];Ten intCount = 1; One Public int[] Generatematrix (intN) { A -result =New int[n][n]; - if(0 = =N) the returnresult; - Spiralorder (result); - returnresult; - } + - Public voidSpiralorder (int[] matrix) { + A at if(Matrix.length = = 1 && matrix[0].length = = 1)//only one element is added directly - { -Matrix[0][0] = count++; - } - Else if(Matrix[0].length = = 1) {//Vertical Bar - for(inti = 0; i < matrix.length; i++){ inMatrix[i][0] = count++; - } to } + Else if(Matrix.length = = 1) {//Horizontal Bar - for(inti = 0; i < matrix[0].length; i++){ theMatrix[0][i] = count++; * } $ }Panax Notoginseng Else { - for(inti = 0; i < matrix[0].length; i++) {//Add first row theMatrix[0][i] = count++; + } A for(inti = 1; i < matrix.length; i++) {//Add last Vertical theMATRIX[I][MATRIX[0].LENGTH-1] = count++; + } - for(inti = matrix[0].length-2; I >= 0; i--) {//Add last Row $Matrix[matrix.length-1][i] = count++; $ } - for(inti = matrix.length-2; I >= 1;i--) {//Add first row -Matrix[i][0] = count++; the } - if(matrix.length-2! = 0 && Matrix[0].length-2! = 0){Wuyi intNext[][] =New int[Matrix.length-2] [Matrix[0].length-2]; theSpiralorder (next);//recursively solves the value of the next matrix - for(inti = 1; i < matrix.length-1; i++){ Wu for(intj = 1; J < matrix[0].length-1;j++){ -MATRIX[I][J] = next[i-1][j-1]; About } $ } - - } - A } + } the}
Spiral Matrix II