您的位置:首页 > 其它

[leetcode 59] Spiral Matrix II--------数组转圈赋值

2016-03-23 22:05 495 查看
Question:

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/2圈即可。

因为矩阵是n*n,所以起点横坐标与纵坐标相等,一圈四个边,所以走四个遍历即可。注意判断循环中的起始点和结束点,与保存。

代码如下:

<span style="font-size:14px;">class Solution {
public:
vector<vector<int>> generateMatrix(int n) {
vector<vector<int>> res(n,vector<int>(n));
if(n <= 0){
return res;
}
helper(res,0,n);
return res;
}
void helper(vector<vector<int>>& res,int pos,int n){
if(pos > n/2)
return ;
int j,i;
for(i = pos; i < n-pos; ++i){//上边的行
res[pos][i] = res[pos][i-1] + 1;
}
--i;
for(j = pos + 1; j < n-pos; ++j){//右边的列
res[j][i] = res[j-1][i] + 1;
}
--j;
for(i = i - 1; i >= pos; --i){//下边的行
res[j][i] = res[j][i+1] + 1;
}
++i;
for(j = j - 1; j > pos; --j){//左边的列
res[j][i] = res[j+1][i] + 1;
}
helper(res,pos+1,n);
}
};</span>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: