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

1 个回答

  • 蓝银皇
    天道忌满,人道忌全。 水满则溢, 物极必反。
    这是 **LeetCode 第 59 题:Spiral Matrix II(螺旋矩阵 II)**。 要求:给定正整数 `n`,生成 `1..n^2` 的顺时针螺旋排列的 `n x n` 矩阵。 # 解法思路(边界收缩) 维护四个边界:`top, bottom, left, right`,按 → ↓ ← ↑ 的顺序填数,每走完一圈收缩边界,直到填满。 ## Java 实现 ```java class Solution { public int[][] generateMatrix(int n) { int[][] ans = new int[n][n]; int top = 0, bottom = n - 1, left = 0, right = n - 1; int num = 1, target = n * n; while (num <= target) { for (int j = left; j <= right; j++) ans[top][j] = num++; // → top++; for (int i = top; i <= bottom; i++) ans[i][right] = num++; // ↓ right--; if (top <= bottom) { for (int j = right; j >= left; j--) ans[bottom][j] = num++; // ← bottom--; } if (left <= right) { for (int i = bottom; i >= top; i--) ans[i][left] = num++; // ↑ left++; } } return ans; } } ``` ## Python 实现 ```python def generateMatrix(n: int) -> list[list[int]]: ans = [[0]*n for _ in range(n)] top, bottom, left, right = 0, n-1, 0, n-1 num, target = 1, n*n while num <= target: for j in range(left, right+1): ans[top][j] = num; num += 1 top += 1 for i in range(top, bottom+1): ans[i][right] = num; num += 1 right -= 1 if top <= bottom: for j in range(right, left-1, -1): ans[bottom][j] = num; num += 1 bottom -= 1 if left <= right: for i in range(bottom, top-1, -1): ans[i][left] = num; num += 1 left += 1 return ans ``` **复杂度**:时间 O(n²),空间 O(1)(不计输出矩阵)。 **示例**:`n=3` → ``` 1 2 3 8 9 4 7 6 5 ```
    发布于 2025-08-12 10:06 •IP属地 吉林
    举报
    评论
    收藏