leetcode专题训练 54. Spiral Matrix

一道模拟题。思路如下:如果右边走到头就往下走,往下走到头就往左走,往左走到头就往上走,往上走到头就往右走,周而复始,直到遍历完矩阵。而判断是否走到头的条件在我的代码中有体现,在对应方向走到对应边界就说明走到头了。走到头后要更新边界,也就是让可以走的地方减少。

class Solution:
    def spiralOrder(self, matrix: List[List[int]]) -> List[int]:
        if not matrix:
            return []
        
        output = []
        
        m_dir = [[0, 1], [1, 0], [0, -1], [-1, 0]]
        up = le = 0
        ri, do = len(matrix[0])-1, len(matrix)-1
        
        i = j = d = 0
        for _ in range((ri+1)*(do+1)):
            output.append(matrix[i][j])
            if j == ri and d == 0:
                d = 1
                up += 1
            elif i == do and d == 1:
                d = 2
                ri -= 1
            elif j == le and d == 2:
                d = 3
                do -= 1
            elif i == up and d == 3:
                d = 0
                le += 1
            i, j = i + m_dir[d][0], j + m_dir[d][1]
        return output
            

你可能感兴趣的:(leetcode)