您的位置:首页 > 其它

59. Spiral Matrix II

2016-06-27 22:28 459 查看
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 ]
]

题意:给一个数n,按螺旋方式把 值1--n^2之间的数填入矩阵。
思路:跟spiral matrix题目一样,重点是对matrix的螺旋式遍历方法。

class Solution {
public:
vector<vector<int>> generateMatrix(int n) {
vector<vector<int>> matrix(n, vector<int>(n));
if (n < 1)
return matrix;
int i = 0;
int j = 0;
int count = 1;
matrix[i][j] = count++;
const int nn = n*n;
while (count <= nn){
//turn right
while (j + 1 < n - i && count <= nn){
matrix[i][++j] = count++;
}
//turn down
while (i + 1 < n - (n - j - 1) && count <= nn){
matrix[++i][j] = count++;
}
//turn left
while (j - 1 >= n - i - 1 && count <= nn){
matrix[i][--j] = count++;
}
//turn up
while (i - 1 >= j + 1 && count <= nn){
matrix[--i][j] = count++;
}
}
return matrix;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  matrix