59. Spiral Matrix II



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 };

 

posted @ 2019-01-05 11:22  乐乐章  阅读(99)  评论(0编辑  收藏  举报