给你一个正整数 n ,生成一个包含 1 到 n2 所有元素,且元素按顺时针顺序螺旋排列的 n x n 正方形矩阵 matrix 。
示例 1:
输入:n = 3
输出:[[1,2,3],[8,9,4],[7,6,5]]
示例 2:
输入:n = 1
输出:[[1]]
提示:
1 <= n <= 20
通过次数132,799提交次数168,447
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/spiral-matrix-ii
python
# 螺旋矩阵II
class Solution:
def spiralMatrixII(self, n: int) -> [[int]]:
"""
模拟行为,时间O(n*n), 空间O(n*n)
思路:
-left > right, row-top, top++
-top > bottom, col-right, right--
-right > left, row-bottom, bottom--
-bottom > top, col-left, left++
:param n:
:return:
"""
top,bottom,left,right = 0,n-1,0,n-1 # init boundary
matrix = [[0 for _ in range(n)] for _ in range(n)] # init matrix
num, target = 1, n*n
while num <= target:
for i in range(left, right+1): # left > right, row-top, top++
matrix[top][i] = num
num += 1
top += 1
for i in range(top, bottom+1): # top > bottom, col-right, right--
matrix[i][right] = num
num += 1
right -= 1
for i in range(right, left-1, -1): # right > left, row-bottom, bottom--
matrix[bottom][i] = num
num += 1
bottom -= 1
for i in range(bottom, top-1, -1): # bottom > top, col-left, left++
matrix[i][left] = num
num += 1
left += 1
return matrix
if __name__ == "__main__":
n = 3
test = Solution()
print(test.spiralMatrixII(n))
golang
package main
import "fmt"
func main() {
n := 3
fmt.Println(spiralMatrixII(n))
}
// 模拟行为,螺旋矩阵II
func spiralMatrixII(n int) [][]int {
matrix := make([][]int, n)
for i := 0; i < n; i++ {
matrix[i] = make([]int, n)
}
top, bottom, left, right := 0, n-1, 0, n-1
num, target := 1, n*n
for num <= target {
for i := left; i <= right; i++ {
matrix[top][i] = num
num++
}
top++
for i := top; i <= bottom; i++ {
matrix[i][right] = num
num++
}
right--
for i := right; i >= left; i-- {
matrix[bottom][i] = num
num++
}
bottom--
for i := bottom; i >= top; i-- {
matrix[i][left] = num
num++
}
left++
}
return matrix
}