标签:
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相似,给定方阵的维度n,返回一个螺旋矩阵。
class Solution {
public:
vector<vector<int> > generateMatrix(int n) {
vector< vector<int> > matrix(n, vector<int>(n));
//begin_row is the row number, end_row is the remaind size of each row
int begin_row = 0, end_row = n - 1;
//begin_col is the col number,end_col is the remaind size of each col
int begin_col = 0, end_col = n - 1;
int num = 1;
while(true){
for(int i = begin_row; i <= end_row; ++i)//left to right
matrix[begin_row][i] = num++;
if(++begin_col > end_col) break;
for(int i = begin_col; i <= end_col; ++i)//up to down
matrix[i][end_row] = num++;
if(begin_row > --end_row) break;
for(int i = end_row; i >= begin_row; --i)//right to left
matrix[end_col][i] = num++;
if(begin_col > --end_col) break;
for(int i = end_col; i >= begin_col; --i)//bottom to up
matrix[i][begin_row] = num++;
if(++begin_row > end_row) break;
}
return matrix;
}
};
标签:
原文地址:http://www.cnblogs.com/zxy1992/p/4279001.html