首页 > 代码库 > Spiral Matrix

Spiral Matrix

Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix 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].

思路:对矩阵进行螺旋式遍历,依次进行向右、向下、向左、向上遍历。重复上述步骤。注意边界条件。

 1 class Solution { 2 public: 3     vector<int> spiralOrder( vector<vector<int>> &matrix ) { 4         if( matrix.empty() || matrix[0].empty() ) { return vector<int>( 0 ); } 5         int rows = matrix.size(), cols = matrix[0].size(), n_iter = ( min( rows, cols ) - 1 ) / 2; 6         vector<int> spiral; 7         for( int step = 0; step <= n_iter; ++step ) { 8             // right 9             for( int j = step; j < cols-step; ++j ) {10                 spiral.push_back( matrix[step][j] );11             }12             // down13             for( int i = step+1; i < rows-step; ++i ) {14                 spiral.push_back( matrix[i][cols-step-1] );15             }16             // left17             if( step < rows-step-1 ) {18                 for( int j = cols-step-2; j >= step; --j ) {19                     spiral.push_back( matrix[rows-step-1][j] );20                 }21             }22             // up23             if( step < cols-step-1 ) {24                 for( int i = rows-step-2; i > step; --i ) {25                     spiral.push_back( matrix[i][step] );26                 }27             }28         }29         return spiral;30     }31 };

 

Spiral Matrix