码迷,mamicode.com
首页 > 其他好文 > 详细

59. Spiral Matrix II

时间:2019-01-05 12:10:41      阅读:136      评论:0      收藏:0      [点我收藏+]

标签:bsp   order   ott   lin   return   generate   desc   line   tor   



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

标签:bsp   order   ott   lin   return   generate   desc   line   tor   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!