题目描述:
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 ]
]
Hide Tags Array
分析:有前一题Sprial Matrix的基础后,该题就思路就明朗了。同样是一层一层的处理,每一层用对角节点做标记。
处理方式跟Sprial Matrix的过程一模一样。请参考上一题
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 ]
]
Hide Tags Array
分析:有前一题Sprial Matrix的基础后,该题就思路就明朗了。同样是一层一层的处理,每一层用对角节点做标记。
处理方式跟Sprial Matrix的过程一模一样。请参考上一题
不过有点不同就是该题是一个方阵,若n为奇数,那么循环处理过后会留有中间节点没有处理,若n为偶数,则不存在未处理的中间节点。
以下是C++实现代码,附带注释:
/*/4ms/*/
class Solution {
public:
struct node /**定义node结构,用于存储每一层的两个对角节点*/
{
int x;
int y;
node(int _x,int _y):x(_x),y(_y){}
};
vector<vector<int>> generateMatrix(int k) {
vector<vector<int>> vec(k,vector<int>(k,0));
node up(0,0);
node down(k-1,k-1);
int lay = k/2;
int n = 1;
while(lay--)
{
for(int j = up.y;j<down.y;j++) /*从左到右处理上边*/
{
vec[up.x][j] = n++;
}
for(int i = up.x;i < down.x;i++) /*从上到下处理右边*/
{
vec[i][down.y] = n++;
}
for(int j = down.y;j >up.y;j--) /*从右到左处理下边*/
{
vec[down.x][j] = n++;
}
for(int i = down.x;i > up.x;i--) /*从下到上处理左边*/
{
vec[i][up.y] = n++;
}
/*更新对角节点*/
up.x++;
up.y++;
down.x--;
down.y--;
}
if(k % 2 == 1) /*处理奇数层留下的中间节点*/
vec[k/2][k/2]=n;
return vec;
}
};