题目
给你一个正整数 n ,生成一个包含 1 到 n2 所有元素,且元素按顺时针顺序螺旋排列的 n x n 正方形矩阵 matrix 。
示例1
输入:n = 3
输出:[[1,2,3],[8,9,4],[7,6,5]]
思路
这个题思路还是比较清晰的,就把螺旋填充的过程看成是分层的过程,一层层深入。
深入的过程中跟踪层数的方法有两种,一种是直接记录层数,一种是记录每一层的边界。
方法一
class Solution {
public int[][] generateMatrix(int n) {
int circle = (n + 1) / 2;
int [][]result = new int[n][n];
int current = 1;
for (int i = 1; i <= circle; i++) {
// 横向
for (int j = i-1; j <= n - i; j++) {
result[i-1][j] = current++;
}
// 纵向
for (int j = i; j < n - i; j++) {
result[j][n - i] = current++;
}
// 横向
for (int j = n - i; j >= i; j--) {
result[n - i][j] = current++;
}
// 纵向
for (int j = n - i; j >= i; j--) {
result[j][i - 1] = current++;
}
}
return result;
}
}
这种记录层数的方法每个方向上都需要重新计算边界,很容易出错。
方法二
class Solution {
public int[][] generateMatrix(int n) {
int circle = (n + 1) / 2;
int [][]result = new int[n][n];
int current = 1;
int left = 0, right = n-1, top = 0, bottom = n-1;
while (left <= right && top <= bottom) {
for (int col = left; col <= right; col++) {
result[top][col] = current++;
}
for (int row = top+1; row < bottom; row++) {
result[row][right] = current++;
}
for (int col = right; col > left; col--) {
result[bottom][col] = current++;
}
for(int row = bottom; row>top;row--) {
result[row][left] = current++;
}
left++;
right--;
top++;
bottom--;
}
return result;
}
}
这是和官方写法基本一致的实现,这种方法的可理解性更高。
难点
其实这里边有一个难点,就是最后一层有可能会出现重复的情况,需要避免。官方的方法是第一个横向边界是直接打通一行[left,right],第一个纵向是(top,bottom],这样就能把最后一层的一个点、一行、一列的情况都cover到,然后leftright || topbottom的情况就是这种情况,后面的一个横向和纵向的赋值逻辑就不执行了。
代码如下:
class Solution {
public int[][] generateMatrix(int n) {
int num = 1;
int[][] matrix = new int[n][n];
int left = 0, right = n - 1, top = 0, bottom = n - 1;
while (left <= right && top <= bottom) {
for (int column = left; column <= right; column++) {
matrix[top][column] = num;
num++;
}
for (int row = top + 1; row <= bottom; row++) {
matrix[row][right] = num;
num++;
}
if (left < right && top < bottom) {
for (int column = right - 1; column > left; column--) {
matrix[bottom][column] = num;
num++;
}
for (int row = bottom; row > top; row--) {
matrix[row][left] = num;
num++;
}
}
left++;
right--;
top++;
bottom--;
}
return matrix;
}
}
作者:LeetCode-Solution
链接:https://leetcode-cn.com/problems/spiral-matrix-ii/solution/luo-xuan-ju-zhen-ii-by-leetcode-solution-f7fp/
其实上面的方法一和方法二是采用了另外一种方式去避免重复赋值的情况。具体方法是第一个横向是[left,right],第一个纵向是(top,bottom),第二个横向是[right,left),第二个纵向是[bottom, top)。这个方法在当前题目下是正确的,但是如果不是一个方形矩阵,其实是有问题的,两个横向和两个纵向有一部分是有可能产生重合的。
所以,还是按照官方给的方法是最正确的逻辑,从解释性和理解性上都是合理的。