# leetcode：Spiral Matrix II

leetcode：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 ]
]

c++实现:

#include <iostream>
#include <vector>

using namespace std;
vector<vector<int> > generateMatrix(int n)
{
vector< vector<int> > matrix(n, vector<int>(n));

if (n == 0)
return matrix;

int beginX = 0, endX = n - 1;
int beginY = 0, endY = n - 1;
int num = 1;
while (true)
{
for (int j = beginX; j <= endX; ++j)
matrix[beginY][j] = num++;
if (++beginY > endY)
break;
for (int i = beginY; i <= endY; ++i)
matrix[i][endX] = num++;
if (beginX > --endX)
break;
for (int j = endX; j >= beginX; --j)
matrix[endY][j] = num++;
if (beginY > --endY)
break;
for (int i = endY; i >= beginY; --i)
matrix[i][beginX] = num++;
if (++beginX > endX)
break;
}
return matrix;
}
int main()
{
vector<vector<int>> vec;
int n=3;
vec=generateMatrix(n);
vector<vector<int>>::iterator pp;
vector<int>::iterator it;
for(pp=vec.begin();pp<vec.end();pp++)
{
for (it=(*pp).begin();it<(*pp).end();it++)
{
cout<<*it<<" ";
}
cout<<endl;
}

return 0;
}

#### 【LeetCode】59. Spiral Matrix II 解题报告

2016-05-15 11:21:35

#### Spiral Matrix II -- LeetCode

2014-03-24 06:54:28

#### [Leetcode]54. Spiral Matrix @python

2016-01-18 21:27:37

#### LeetCode 59. Spiral Matrix II (JAVA)（螺旋矩阵2）

2017-04-17 16:10:52

#### 59. Spiral Matrix II Leetcode Python

2015-02-03 23:48:58

#### [LeetCode]59.Spiral Matrix II

2015-02-04 22:25:02

#### [leetcode] 59. Spiral Matrix II 解题报告

2016-01-02 11:25:25

#### leetCode 59.Spiral Matrix II (螺旋矩阵II) 解题思路和方法

2015-07-15 14:14:59

#### 【LeetCode】54. Spiral Matrix 解题报告

2016-05-15 10:28:27

#### 《leetcode》spiral-matrix-ii（构造螺旋矩阵）

2017-08-29 11:14:18