Topic One:
Given a matrix of m x n elements (m rows, n columns), return all elements of the Matri X in Spiral Order.
For example,
Given the following matrix:
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
You should return [1,2,3,6,9,8,7,4,5]
.
Answer:
A method that operates from the outermost layer to the inside.
Public classSolution { PublicList<integer> Spiralorder (int[] matrix) {List<Integer> res =NewArraylist<>(); if(matrix==NULL|| matrix.length==0| | matrix[0].length==0)returnRes; //The coordinates of the number in the upper left corner of each lap are (top,left), the coordinates of the number in the lower right corner are (bottom,right) inttop = 0, left = 0; intBottom = matrix.length-1, right = Matrix[0].length-1; while(Top <= Bottom && left <=Right ) {Outedge (res, matrix, left+ +, top++, right--, bottom--); } returnRes; } Private Static voidOutedge (list<integer> Res,int[] Matrix,intLeftintTopintRightintbottom) { if(top = =bottom) { for(inti = left; I <= right; i++) {Res.add (matrix[top][i]); } } Else if(left = =Right ) { for(inti = top; I <= bottom; i++) {Res.add (matrix[i][left]); } } Else { intCurrow =top; intCurcol =Left ; while(Curcol <Right ) {Res.add (Matrix[top][curcol++]); } while(Currow <bottom) {Res.add (Matrix[currow++][right]); } while(Curcol >Left ) {Res.add (Matrix[bottom][curcol--]); } while(Currow >top) {Res.add (Matrix[currow--][left]); } } }}
Topic Two:
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]]
Public Static int[] Generatematrix (intN) {int[] res =New int[N][n]; inttop = 0, left = 0; intBottom = n-1, right = N-1; intnum = 1; while(left<=right&&top<=bottom) {num= Inputedge (num, res, left++, top++, right--, bottom--); } returnRes; } Private Static intInputedge (intNumint[] Res,intLeftintTopintRightintbottom) { intCurrow =top; intCurcol =Left ; if(top==bottom&&left==Right ) {Res[top][left]=num; returnnum; } while(Curcol <Right ) {Res[top][curcol+ +] = num++; } while(Currow <bottom) {Res[currow++][right] = num++; } while(Curcol >Left ) {Res[bottom][curcol--] = num++; } while(Currow >top) {Res[currow--][left] = num++; } returnnum; }
[Algorithmic] rotation matrix problem (Spiral matrix)