59. 螺旋矩阵 II
题目
原题链接:https://leetcode-cn.com/problems/spiral-matrix-ii/
给你一个正整数\(n\),生成一个包含\(1\)到\(n^2\)所有元素,且元素按顺时针顺序螺旋排列的\(n\times n\)正方形矩阵matrix。
输入:n = 3
输出:[[1,2,3],[8,9,4],[7,6,5]]
解题思路
-
生成一个\(n×n\)空矩阵
matrix,随后模拟整个向内环绕的填入过程:-
定义当前左右上下边界:
left, right, top, bottom,初始值\(num = 1\),迭代终止值\(endValue = n * n\); -
当\(num <= endValue\)时,始终按照从左到右、从上到下、从右到左、从下到上填入顺序循环,每次填入后:
- 执行\(num += 1\):得到下一个需要填入的数字;
- 更新边界:例如从左到右填完后,上边界\(top += 1\),相当于上边界向内缩1。
-
使用\(num <= tar\)而不是
left < right || top < bottom作为迭代条件,是为了解决当\(n\)为奇数时,矩阵中心数字无法在迭代过程中被填充的问题。
-
-
最终返回
matrix即可。
代码实现
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
/**
* 59. 螺旋矩阵 II
* @author chenzufeng
*/
public class No59_GenerateMatrix {
public static void main(String[] args) {
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(reader.readLine());
for (int[] row : generateMatrix(n)) {
for (int column : row) {
System.out.print(column + " ");
}
System.out.println();
}
} catch (IOException e) {
e.printStackTrace();
}
}
public static int[][] generateMatrix(int n) {
int left = 0, right = n - 1, top = 0, bottom = n - 1;
int[][] result = new int[n][n];
int num = 1, endValue = n * n;
while (num <= endValue) {
// 1.顶部行——从左到右,列column在变,边界为left到right
for (int column = left; column <= right; column++) {
result[top][column] = num++;
}
top++;
// 2.右边列——从上到下,行row在变,边界为top到bottom
for (int row = top; row <= bottom; row++) {
result[row][right] = num++;
}
right--;
// 3.底部行——从右往左遍历:列column在变,边界为right到left
for (int column = right; column >= left; column--) {
result[bottom][column] = num++;
}
bottom--;
// 4.左边列——从下往上遍历,行row在变,边界为bottom到top
for (int row = bottom; row >= top; row--) {
result[row][left] = num++;
}
left++;
}
return result;
}
}

浙公网安备 33010602011771号