每日一题20250207-LC59

题目信息

目难度:中等 掌握程度:🌟🌟🌟🌟

59. 螺旋矩阵 II - 力扣(LeetCode)

给你一个正整数 n ,生成一个包含 1 到 n2 所有元素,且元素按顺时针顺序螺旋排列的 n x n 正方形矩阵 matrix 。

示例 1:

123
894
765

输入:n = 3 输出:[[1,2,3],[8,9,4],[7,6,5]] 示例 2:

输入:n = 1 输出:\[[1]\]

提示:

1 <= n <= 20

解题思路

模拟,舍得用变量,用 4 个变量分别控制 上、下、左、右 四个边界

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
class Solution {
    public int[][] generateMatrix(int n) {
        int[][] res = new int[n][n];
        int num = 1;
        // 确定边界范围
        int top = 0 , bottom = n-1;
        int left = 0 , right = n-1;
        while(num <= n*n){
            //top left -> top right
            for(int i = left ; i <= right ; i++){
                res[top][i] = num++;
            }
            top++;
            //top right -> bottom right
            for(int i = top ; i <= bottom ; i++){
                res[i][right] = num++;
            }
            right--;
            //bottom right -> bottom left
            for(int i = right ; i >= left ;i --){
                res[bottom][i] = num++;
            }
            bottom--;
            //bottom left -> top left
            for(int i = bottom ; i >= top; i--){
                res[i][left] = num++;
            }
            left++;
        }
        return res;
    }
}
updatedupdated2025-02-152025-02-15