Leetcode 59 Spiral Matrix II
来源:程序员人生 发布时间:2016-12-12 15:17:39 阅读次数:2315次
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 ]
]
方阵蛇形填数
和上1道蛇形取数差不多。
http://blog.csdn.net/accepthjp/article/details/52577112
class Solution {
public:
vector<vector<int>> generateMatrix(int n) {
vector<int> row(n,0);
vector<vector<int>> result(n,row);
int rows=n,cols=n,cnt=0;
for(int x=0,y=0;x<rows && y<cols;x++,y++)
{
for(int i=y;i<cols;i++) result[x][i]=++cnt;
for(int i=x+1;i<rows;i++) result[i][cols⑴]=++cnt;
for(int i=cols⑵;i>=y;i--) result[rows⑴][i]=++cnt;
for(int i=rows⑵;i>x;i--) result[i][y]=++cnt;
rows--;
cols--;
}
return result;
}
};
生活不易,码农辛苦
如果您觉得本网站对您的学习有所帮助,可以手机扫描二维码进行捐赠