Problem statement

https://binarysearch.com/problems/Spiral-Matrix/

Solution

Equal to Leetcode 0054. Spiral Matrix.

Complexity

It is O(mn) both for time and space.

Code

class Solution:
    def solve(self, matrix):
        if not matrix: return []
        n, m = len(matrix[0]), len(matrix)
        x, y, dx, dy = 0, 0, 1, 0
        ans = []
        for _ in range(m*n):
            if not 0 <= x+dx < n or not 0 <= y+dy < m or matrix[y+dy][x+dx] == "*":
                dx, dy = -dy, dx
                
            ans.append(matrix[y][x])
            matrix[y][x] = "*"
            x, y = x + dx, y + dy
        
        return ans