【Spiral Matrix II】cpp
题目:
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 ] ]
代码:
class Solution { public: vector<vector<int>> generateMatrix(int n) { vector<vector<int> > ret(n, vector<int>(n,0)); int circle = n/2; int v = 1; for ( int c=0; c<circle; ++c ) { // up for ( int col=c; col<n-c; ++col ) ret[c][col]=v++; // right for ( int row=c+1; row<n-c-1; ++row ) ret[row][n-1-c]=v++; // down for ( int col=n-1-c; col>=c; --col ) ret[n-1-c][col]=v++; // left for ( int row=n-2-c; row>c; --row) ret[row][c]=v++; } if ( n & 1 ) { ret[circle][circle]=v; } return ret; } };
tips:
按照Spiral Matrix的顺序走一遍元素,维护一个v每次运算后+1。
============================================
第二次过这道题,思路跟第一次一样。
class Solution { public: vector<vector<int>> generateMatrix(int n) { vector<vector<int> > ret(n, vector<int>(n,1)); if ( n<1 ) return ret; int val = 1; for ( int i=0; i<n/2; ++i ) { // north for ( int p=i; p<n-i; ++p ) ret[i][p] = val++; // east for ( int p=i+1; p<n-1-i; ++p ) ret[p][n-1-i] = val++; // south for ( int p=i; p<n-i; ++p ) ret[n-1-i][n-1-p] = val++; // west for ( int p=i+1; p<n-1-i; ++p ) ret[n-1-p][i] = val++; } if ( n & 1 ) ret[n/2][n/2] = val; return ret; } };