您的位置:首页 > 其它

[59] Spiral Matrix II

2015-08-25 17:38 316 查看

1. 题目描述

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 ]

]

题目的意思是,给定一个数字n,输出一个以螺旋方式填满的n*n的二维数组

2. 解题思路

采用螺旋排列时的顺序为,右->下->左->上,都是走到头后换下一个方向,直到四个方向都无法前进则数组填充完成。

3. Code

class Solution {
public:
vector<vector<int>> generateMatrix(int n) {
vector<vector <int> > matrix(n ,vector<int>(n,0));    //n*n的二维vector,所有元素为0
if(n == 0)
return matrix;
// 右下左上
bool flag = true;  // 标记当前填充是否完成
string des[4] = {"right", "down", "left", "up"}; // right->down->left->up
int choose = 0;  // 当前方向
string curDes = des[choose%4];
int i(0), j(0);  // i->行 j->列
int count(1);
matrix[0][0] = 1;
if(n == 1)
return matrix;
while(flag)
{
int num(0);
while(curDes == "right")
{
// 没有越界且右边是0
if(j < n-1 && (matrix[i][j+1] == 0))
{
matrix[i][++j] = ++count;
num++;
}
else
{
curDes = des[++choose%4];  // 换方向
}
if(num == 0)
return matrix;
}
while(curDes == "down")
{
// 没有越界且下边是0
if(i < n-1 && (matrix[i+1][j] == 0))
{
matrix[++i][j] = ++count;
}
else
{
curDes = des[++choose%4];  // 换方向
}
}
while(curDes == "left")
{
// 没有越界且左边是0
if(j > 0 && (matrix[i][j-1] == 0))
{
matrix[i][--j] = ++count;
}
else
{
curDes = des[++choose%4];  // 换方向
}
}
while(curDes == "up")
{
// 没有越界且上边是0
if(i > 0 && (matrix[i-1][j] == 0))
{
matrix[--i][j] = ++count;
}
else
{
curDes = des[++choose%4];  // 换方向
}
}
}
}
};


4. 学到的知识

学到了一个创建并初始化m*n的vector二维数组的方式,使用vector的构造函数matrix(int num, int value)

//m*n的二维vector,所有元素为0
vector<vector <int> > matrix(m ,vector<int>(n,0));
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: