Leetcode 921 Solution

This article provides solution to leetcode question 921 (spiral-matrix-iii)

https://leetcode.com/problems/spiral-matrix-iii

Solution

class Solution:
    def spiralMatrixIII(self, R: int, C: int, r0: int, c0: int) -> List[List[int]]:
        directions = [
            (0, 1),
            (1, 0),
            (0, -1),
            (-1, 0),
        ]

        cur_dir = 0
        ans = []
        step = 1
        r = r0
        c = c0
        while len(ans) < R * C:
            for _ in range(2):
                for i in range(step):
                    if 0 <= r < R and 0 <= c < C:
                        ans.append((r, c))
                        if len(ans) == R * C:
                            return ans
                    r += directions[cur_dir][0]
                    c += directions[cur_dir][1]
                cur_dir = (cur_dir + 1) % 4
            step += 1