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 ] ]
vector<vector<int> > generateMatrix(int n) { // Start typing your C/C++ solution below // DO NOT write int main() function vector<vector<int> > matrix; if(n<=0) return matrix; int i,j; for(i=0;i<n;i++) matrix.push_back(vector<int>(n)); int start = 0; int cnt = 1; while(n>2*start) { int end = n-1-start; for(i=start;i<=end;i++) matrix[start][i] = cnt++; for(i=start+1;i<=end;i++) matrix[i][end] = cnt++; for(i=end-1;i>=start;i--) matrix[end][i] = cnt++; for(i=end-1;i>start;i--) matrix[i][start] = cnt++; ++start; } return matrix; }
原文链接: https://www.cnblogs.com/summer-zhou/p/3244257.html
欢迎关注
微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍
![Spiral Matrix II](https://www.ccppcoding.com/wp-content/themes/justnews/themer/assets/images/lazy.png)
原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/98939
非原创文章文中已经注明原地址,如有侵权,联系删除
关注公众号【高性能架构探索】,第一时间获取最新文章
转载文章受原作者版权保护。转载请注明原作者出处!