LeetCode 59. Spiral Matrix II(Python)

来源:互联网 发布:阿里云未备案域名解析 编辑:程序博客网 时间:2024/05/30 04:55

题目描述:
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 ]
]

思路:
螺旋式绕圈赋值即可,停止条件即当所有均赋值完。

AC代码:

    def generateMatrix(self, n):        """        :type n: int        :rtype: List[List[int]]        """        if n == 0:            return []        res = [[0 for x in range(n)] for x in range(n)]        cnt, choice = 1, 0        i, j = 0, 0        weight = 1        res[0][0] = 1        while cnt < n * n:            if choice == 0:                j += 1                res[i][j] = cnt + 1                if j == n - weight:                    choice = 1            elif choice == 1:                i += 1                res[i][j] = cnt + 1                if i == n - weight:                    choice = 2            elif choice == 2:                j -= 1                res[i][j] = cnt + 1                if j == weight - 1:                    choice = 3                    weight += 1            elif choice == 3:                i -= 1                res[i][j] = cnt + 1                if i == weight - 1:                    choice = 0            cnt += 1        return res