首页 > 其他 > 详细

59. Spiral Matrix II

时间:2019-01-05 11:33:17      阅读:131      评论:0      收藏:0      [点我收藏+]


Given a positive integer n, generate a square matrix filled with elements from 1 to n2 in spiral order.

Example:

Input: 3
Output:
[
 [ 1, 2, 3 ],
 [ 8, 9, 4 ],
 [ 7, 6, 5 ]
]



 1 class Solution {
 2 public:
 3     vector<vector<int>> generateMatrix(int n) {
 4         vector<vector<int> > res( n, vector<int>(n) );
 5         int n1 =1;
 6         int c1=0,c2=n-1;
 7         int r1=0,r2=n-1;
 8         while(c1<=c2&&r1<=r2){
 9             for(int c =c1;c<=c2;c++,n1++) res[r1][c] =n1;
10             for(int r =r1+1;r<=r2;r++,n1++) res[r][c2] =n1;
11             if(c1<=c2&&r1<=r2){
12             for(int c =c2-1;c>=c1;c--,n1++) res[r2][c] =n1;
13             for(int r =r2-1;r>=r1+1;r--,n1++) res[r][c1] =n1;
14             }
15             c1++;c2--;r1++;r2--;
16         }
17         return res;
18     }
19 
20 };

 

59. Spiral Matrix II

原文:https://www.cnblogs.com/zle1992/p/10223754.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!