给你一个正整数 n
,生成一个包含 1
到 n2
所有元素,且元素按顺时针顺序螺旋排列的 n x n
正方形矩阵 matrix
。
输入:n = 3 输出:[[1,2,3],[8,9,4],[7,6,5]]
示例 2:
输入:n = 1 输出:[[1]]
讨论:
在尝试解决这个问题时,我最初的想法是寻找一个整体填充每个值的模式,可以通过一些技巧来更新矩阵。然而,我一直没有想出一个巧妙的解决方案。从这个经验可以学到,如果没有一个巧妙的思路,就应该尽可能先使用能想到的暴力解法(brute force)来尝试解决问题,然后再思考可能的优化空间。
在实现过程中,需要特别注意当 n 为奇数时,如何正确处理矩阵中心的值。我在实现中没有正确的处理中心值,并且判断条件也没有正确设置循环终止条件,导致进入了死循环。为了避免这种情况,我们需要多尝试画图测试几个实际的例子,然后总结归纳出具体的实现方法。
When I first attempted to solve this problem, my initial thought was to find a pattern for filling in each value of the matrix as a whole, which could be updated with some tricks. However, I couldn't come up with a clever solution. From this experience, I learned that if I don't have a clever approach in mind, I should try to solve the problem using a brute force method that I can think of, and then consider possible optimizations later.
During the implementation, it's important to pay special attention to how to correctly handle the center value when n is odd. In my initial implementation, I didn't handle the center value correctly and also didn't set the loop termination condition properly, resulting in an infinite loop. To avoid this situation, we need to try several actual examples and then summarize and deduce the specific implementation method.
class Solution {
public:
vector<vector<int>> generateMatrix(int n) {
if (n == 1) return { {1} };
vector<vector<int>> solution(n, vector<int>(n, 0));
int sqr = n * n, counter = 1;
int start_x = 0, start_y = 0, end_x = n - 1, end_y = n - 1;
while (sqr > counter) { // 之前写成了sqr >= counter,没有考虑到n为奇数的情况以及处理boundary的问题,导致infinity loop,不会退出
for (int i = start_x; i < end_x; i++) {
solution[start_y][i] = counter++;
}
for (int j = start_y; j < end_y; j++) {
solution[j][end_x] = counter++;
}
for (int i = end_x; i > start_x; i--) {
solution[end_y][i] = counter++;
}
for (int j = end_y; j > start_y; j--) {
solution[j][start_x] = counter++;
}
start_x++;
start_y++;
end_x--;
end_y--;
}
if (n % 2 == 1) {
solution[n / 2][n / 2] = n * n;
}
return solution;
}
};