Given a matrix containing m x n elements (m rows, n columns), return all elements in the matrix in a clockwise spiral order.
Example 1:
Input: [[1, 2, 3], [4, 5, 6], [7, 8, 9]] output: [1,2,3,6,9,8,7,4,5]
Example 2:
Input: [ [1, 2, 3, 4], [5, 6, 7, 8], [9,10,11,12]] Output: [1,2,3,4,8,12,11,10,9,5,6,7]
Friendship Tip: My solution is rather slow ...
classSolution { Public: /*1234 5678 9876 5432*/Vector<int> Spiralorder (vector<vector<int>>&matrix) { //there seems to be no regularity, for a matrix, record its starting point, 0, 0, constitute a m*n, first output first line, then output the last column of n-2, then output the last row, and then output the first column of N-2//then modify the starting point to 1,1,m,n for M-2,n-2 if(matrix.size () = =0)return {}; Vector<int>result; Spiralorder (Matrix,result,0,0, Matrix.size (), matrix[0].size ()); returnresult; } voidSpiralorder (vector<vector<int>>& matrix,vector<int>& result,intXintYintMintN) {if(m<=0|| n<=0)return; if(M = =1|| n = =1) { for(inti =0; I! = m; ++i) for(intj =0; J! = N; ++j) Result.push_back (Matrix[x+ I][y +J]); return; } for(inti =0; i<n; ++i) result.push_back (matrix[x+0][y +i]); for(inti =1; I<m-1; ++i) result.push_back (matrix[x+ I][y + N-1]); for(inti = n-1; I >=0; --i) result.push_back (matrix[x+ M-1][y +i]); for(inti = m-2; i >0; --i) result.push_back (matrix[x+ I][y +0]); M-=2; N-=2; Spiralorder (Matrix, result, x+1, Y +1, M, N); } };
leetcode#54 Spiral Matrix