Given an integer n, generate a square matrix filled with elements from 1 to n2 in spiral order.
For example,Given n = 3,
You should return the following matrix:
[
[ 1, 2, 3 ],
[ 8, 9, 4 ],
[ 7, 6, 5 ]
]
思路:
1. 判断特殊情况,n=0或1
2. 定义左右上下边界,依次填充数组;动态更新边界,继续填充,直到左右边界重合或上下边界重合。
3. 注意每次填充的前提是num小于n*n
代码(Python):时间 O(n), 空间 O(n)
class Solution(object):
def generateMatrix(self, n):
"""
:type n: int
:rtype: