LeetCode 59. Spiral Matrix II

LeetCode 59. Spiral Matrix II - Answer LeetCode编程练习解答

Description

Spiral Matrix II

Given a positive integer n, generate a square matrix filled with elements from 1 to n^2 in spiral order.

Example:

1
2
3
4
5
6
7
Input: 3
Output:
[
 [ 1, 2, 3 ],
 [ 8, 9, 4 ],
 [ 7, 6, 5 ]
]

Solution

This problem is very similar to 54. Spiral Matrix.

Just replace function append_ans to mark_idx:

1
2
3
4
5
idx := 1
mark_idx := func(x, y int) {
    matrix[x][y] = idx
    idx++
}

Similar Problem

使用 Hugo 构建
主题 StackJimmy 设计