LeetCode解题之Spiral Matrix II


原题

将一个正方形矩阵螺旋着填满递增的数字。

注意点:

样例:

输入: n = 3

输出:
[
[ 1, 2, 3 ],
[ 8, 9, 4 ],
[ 7, 6, 5 ]
]

解题思路

这道题跟 Spiral Matrix 正好相反,一个是螺旋着读出数字。一个是螺旋着写入数字,并且这道题还要简单一点,由于形状固定是正方形的。所以仅仅要控制四条边不断向内缩进就能够了。考虑一下奇偶的情况,在奇数的时候要额外加一个中心点。

AC源代码

class Solution(object):
    def generateMatrix(self, n):
        """
        :type n: int
        :rtype: List[List[int]]
        """
        left = top = 0
        right = n - 1
        bottom = n - 1
        num = 1
        result = [[0 for __ in range(n)] for __ in range(n)]
        while left < right and top < bottom:
            for i in range(left, right):
                result[top][i] = num
                num += 1
            for i in range(top, bottom):
                result[i][right] = num
                num += 1
            for i in range(right, left, -1):
                result[bottom][i] = num
                num += 1
            for i in range(bottom, top, -1):
                result[i][left] = num
                num += 1
            left += 1
            right -= 1
            top += 1
            bottom -= 1
        if left == right and top == bottom:
            result[top][left] = num
        return result


if __name__ == "__main__":
    assert Solution().generateMatrix(5) == [[1, 2, 3, 4, 5], [16, 17, 18, 19, 6], [15, 24, 25, 20, 7],
                                            [14, 23, 22, 21, 8], [13, 12, 11, 10, 9]]

欢迎查看我的Github (https://github.com/gavinfish/LeetCode-Python) 来获得相关源代码。