885. Spiral Matrix III - cocoder39/coco39_LC GitHub Wiki

885. Spiral Matrix III

class Solution:
    def spiralMatrixIII(self, rows: int, cols: int, rStart: int, cStart: int) -> List[List[int]]:
        res = [(rStart, cStart)]
        k = 1
        while len(res) < rows * cols:
            for dr, dc, dk in [(0, 1, k), (1, 0, k), (0, -1, k+1), (-1, 0, k+1)]:
                for _ in range(dk):
                    rStart += dr
                    cStart += dc
                
                    if 0 <= rStart < rows and 0 <= cStart < cols:
                        res.append((rStart, cStart))
                        if len(res) == rows * cols:
                            return res
            k += 2
            
        return res