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

【leetcode】Spiral Matrix II

时间:2015-01-08 21:32:10      阅读:209      评论:0      收藏:0      [点我收藏+]

标签:

Spiral Matrix II

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 ]
]
 
与Spiral Matrix类似:
 
 1 class Solution {
 2 public:
 3     vector<vector<int> > generateMatrix(int n) {
 4        
 5         int x1=0;
 6         int y1=0;
 7         int x2=n-1;
 8         int y2=n-1;
 9        
10         int count=0;
11         vector<vector<int>> result(n,vector<int>(n));
12         while(count<n*n)
13         {
14            
15             for(int j=y1;j<=y2;j++)
16             {
17                 count++;
18                 result[x1][j]=count;
19             }              
20             for(int i=x1+1;i<=x2;i++)
21             {
22                 count++;
23                 result[i][y2]=count;
24             }
25            
26             for(int j=y2-1;j>=y1;j--)
27             {
28                 count++;
29                 result[x2][j]=count;
30             }
31            
32             for(int i=x2-1;i>x1;i--)
33             {
34                 count++;
35                 result[i][x1]=count;
36             }
37            
38             x1++;y1++;x2--;y2--;
39         }
40        
41         return result;
42        
43        
44     }
45 };

 

【leetcode】Spiral Matrix II

标签:

原文地址:http://www.cnblogs.com/reachteam/p/4211840.html

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