标签:style blog http io ar color sp for strong
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 ] ]
与Spiral Matrix实现基本一致,只不过上题是遍历输出,这题是遍历输入。
class Solution { public: vector<vector<int> > generateMatrix(int n) { //n by n matrix vector<vector<int> > matrix(n, vector<int>(n,0)); if(n == 0) return matrix; int level = (n%2==0)?(n/2):(n/2+1); int number = 1; for(int i = 0; i < level; i ++) { //from up-left to up-right for(int j = i; j < n-i; j ++) matrix[i][j] = number++; //from up-right to down-right for(int j = i+1; j < n-i; j ++) matrix[j][n-1-i] = number++; //from down-right to down-left for(int j = n-1-i-1; j >= i; j --) matrix[n-1-i][j] = number++; //from down-left to up-left for(int j = n-1-i-1; j > i; j --) matrix[j][i] = number++; } return matrix; } };
标签:style blog http io ar color sp for strong
原文地址:http://www.cnblogs.com/ganganloveu/p/4157415.html