LeetCode-Python-59. 螺旋矩阵 II

给定一个正整数 n,生成一个包含 1 到 n2 所有元素,且元素按顺时针顺序螺旋排列的正方形矩阵。

示例:

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

 

思路:

模拟法,用方向变量来改变前进方向。类似LeetCode-Python-54. 螺旋矩阵中的第二种思路。

class Solution(object):
    def generateMatrix(self, n):
        """
        :type n: int
        :rtype: List[List[int]]
        """
        
        res = [[0 for i in range(n)] for j in range(n)]
        
        i, j, di, dj = 0, 0, 0, 1
        for number in range(1, n ** 2 + 1):
            res[i][j] = number            
            if res[(i + di) % n][(j + dj) % n] != 0: #需要转向
                di, dj = dj, - di  #0 1 变 1 0, 1 0 变 0 -1, 0 -1 变 -1, 0, -1 0 变 0 1                 
            i += di
            j += dj
            
        return res
            

第二种思路:

用有限状态机写。

class Solution(object):
    def spiralOrder(self, matrix):
        """
        :type matrix: List[List[int]]
        :rtype: List[int]
        """
        if not matrix or not matrix[0]:
            return []
        m, n = len(matrix), len(matrix[0])
        i, j = 0, 0
        state = "right"
        cnt = 0
        res = []
        while(cnt < m * n):
            cnt += 1
            res.append(matrix[i][j])
            matrix[i][j] = "X"
            if state == "right":
                j += 1
                if j == n or matrix[i][j] == "X":
                    i += 1
                    j -= 1
                    state = "down"
            elif state == "down":
                i += 1
                if i == m or matrix[i][j] == "X":
                    i -= 1
                    j -= 1
                    state = "left"
            elif state == "left":
                j -= 1
                if j == -1 or matrix[i][j] == "X":
                    j += 1
                    i -= 1
                    state = "up"
            elif state == "up":
                i -= 1
                if i == -1 or matrix[i][j] == "X":
                    i += 1
                    j += 1
                    state = "right"
        return res

 

你可能感兴趣的:(Leetcode)