首页 > 代码库 > Spiral Matrix II

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 ]]

思路:使用for循环依次向右、向下、向左、向上设置矩阵对应位置的值。注意边界条件。

 1 class Solution { 2 public: 3     vector<vector<int>> generateMatrix( int n ) { 4         vector<vector<int>> matrix( n, vector<int>( n, 0 ) ); 5         int val = 1; 6         for( int step = 0; step < (n+1)/2; ++step ) { 7             for( int j = step; j < n-step; ++j ) { 8                 matrix[step][j] = val++; 9             }10             for( int i = step+1; i < n-step; ++i ) {11                 matrix[i][n-step-1] = val++;12             }13             for( int j = n-step-2; j >= step; --j ) {14                 matrix[n-step-1][j] = val++;15             }16             for( int i = n-step-2; i > step; --i ) {17                 matrix[i][step] = val++;18             }19         }20         return matrix;21     }22 };

 

Spiral Matrix II