Spiral Matrix

Problem Id: 54 Difficulty: Medium Tag: Array


Intuition

Just use brute force to solve this problem. Be careful with all edges.

Solution


class Solution:
    def spiralOrder(self, matrix: List[List[int]]) -> List[int]:
        if not matrix:
            return []
        m = len(matrix)
        n = len(matrix[0])
        lo_x, hi_x, lo_y, hi_y = 0, m - 1, 0, n - 1
        x, y = 0, 0
        direction = 0
        ans = []
        while True:
            if lo_x > hi_x or lo_y > hi_y:
                ans.append(matrix[x][y])
                break

            if direction == 0:
                if y == hi_y:
                    direction = 1
                    lo_x += 1
                    continue
                ans.append(matrix[x][y])
                y += 1
            elif direction == 1:
                if x == hi_x:
                    direction = 2
                    hi_y -= 1
                    continue
                ans.append(matrix[x][y])
                x += 1
            elif direction == 2:
                if y == lo_y:
                    direction = 3
                    hi_x -= 1
                    continue
                ans.append(matrix[x][y])
                y -= 1
            else:
                if x == lo_x:
                    direction = 0
                    lo_y += 1
                    continue
                ans.append(matrix[x][y])
                x -= 1
        return ans