LeetCode 59. Spiral Matrix II

Given a positive integer n, generate a square matrix filled with elements from 1 to n2 in spiral order.

Example:

Input: 3
Output:
[
[ 1, 2, 3 ],
[ 8, 9, 4 ],
[ 7, 6, 5 ]
]

解析:
此题目思路跟LeetCode 54思路一致,也是沿着四周开始赋值,思路在这里就不重新介绍了,直接看代码吧。
[cc lang=”C++”]
class Solution {
public:
vector> generateMatrix(int n) {
vector > result(n,vector(n, 0));
int row_begin=0, col_begin = 0;
int row_end=n-1, col_end = n-1;
int index =0;
int max_num = pow(n,2);
while(index <= max_num && col_end >=col_begin && row_end >= row_begin)
{
for(int j=col_begin; j <= col_end; j++) { result[row_begin][j] = ++index; } row_begin ++; for(int j = row_begin; j<= row_end; j++) { result[j][col_end] = ++ index; } col_end --; for(int j = col_end; j >= col_begin; j–)
{
result[row_end][j] = ++ index;
}
row_end –;
for(int j=row_end; j >= row_begin; j–)
{
result[j][col_begin] = ++ index;
}
col_begin ++;
}
return result;

}
};
[/cc]

Add a Comment

邮箱地址不会被公开。 必填项已用*标注

此站点使用Akismet来减少垃圾评论。了解我们如何处理您的评论数据