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

【leetcode】Spiral Matrix II

时间:2015-05-03 20:36:52      阅读:125      评论:0      收藏:0      [点我收藏+]

标签:

Given an integer n, generate a square matrix filled with elements from 1 to n^2 in spiral order.

For example,
Given n = 3,

You should return the following matrix:
[
[ 1, 2, 3 ],
[ 8, 9, 4 ],
[ 7, 6, 5 ]
]

 

 1 class Solution {
 2 public:
 3     vector<vector<int> >generateMatrix(int n) {
 4         int m=0;
 5         vector<vector<int> >a;
 6         a.resize(n,vector<int>(n));
 7         if(n==0)
 8             return a;
 9         int x=0;
10         int y=0;
11         m=a[0][0]=1;
12 
13         while(m<n*n)
14         {
15             while(y<n-1&&!a[x][y+1])
16             {
17                 m++;
18                 y++;
19                 a[x][y]=m;
20             }
21             while(x<n-1&&!a[x+1][y])
22             {
23                 m++;
24                 x++;
25                 a[x][y]=m;
26             }
27            
28             while(y-1>=0&&!a[x][y-1])
29             {
30                 m++;
31                 y--;
32                 a[x][y]=m;
33             }
34 
35             while(x-1>=0&&!a[x-1][y])
36             {
37                 m++;
38                 x--;
39                 a[x][y]=m;
40             }
41         }   
42 
43         return a;
44     }
45 };

 

【leetcode】Spiral Matrix II

标签:

原文地址:http://www.cnblogs.com/jawiezhu/p/4474572.html

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