螺旋矩陣 II

給定一個正整數 n,生成一個包含 1 到 n2 所有元素,且元素按順時針順序螺旋排列的正方形矩陣。

示例:

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

class Solution:

    def generateMatrix(self, n):
        """
        :type n: int
        :rtype: List[List[int]]
        """
        arr = []
        for x in range(n):
            tmp = []
            for y in range(n):
                tmp.append(0)
            arr.append(tmp)
        symbol = 1
        border = n - 1
        row = 0
        col = 0
        count = 1
        total = n * n
        arr[int(n / 2)][int(n / 2)] = n * n
        if n % 2 == 1:
            total = total - 1
        while count <= total:
            if symbol == 1:
                for index in range(border):
                    arr[row][col] = count
                    col += 1
                    count = count + 1
                symbol = 2
            elif symbol == 2:
                for index in range(border):
                    arr[row][col] = count
                    row = row + 1
                    count = count + 1
                symbol = 3
            elif symbol == 3:
                for index in range(border):
                    arr[row][col] = count
                    col = col - 1
                    count = count + 1
                symbol = 4
            elif symbol == 4:
                for index in range(border):
                    arr[row][col] = count
                    row = row - 1
                    count = count + 1
                row = row + 1
                border = border - 2
                symbol = 1
                col = col + 1
        return arr




發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章