algo/leetcode

885. Spiral Matrix III

sourmc 2024. 8. 15. 14:23

[Problem]

You start at the cell (rStart, cStart) of an rows x cols grid facing east. The northwest corner is at the first row and column in the grid, and the southeast corner is at the last row and column.

You will walk in a clockwise spiral shape to visit every position in this grid. Whenever you move outside the grid's boundary, we continue our walk outside the grid (but may return to the grid boundary later.). Eventually, we reach all rows * cols spaces of the grid.

Return an array of coordinates representing the positions of the grid in the order you visited them.

 

Example 1:

 

Input: rows = 1, cols = 4, rStart = 0, cStart = 0

Output: [[0,0],[0,1],[0,2],[0,3]]

Example 2:

 

Input: rows = 5, cols = 6, rStart = 1, cStart = 4

Output: [[1,4],[1,5],[2,5],[2,4],[2,3],[1,3],[0,3],[0,4],[0,5],[3,5],[3,4],[3,3],[3,2],[2,2],[1,2],[0,2],[4,5],[4,4],[4,3],[4,2],[4,1],[3,1],[2,1],[1,1],[0,1],[4,0],[3,0],[2,0],[1,0],[0,0]]

 

Constraints:

  • 1 <= rows, cols <= 100
  • 0 <= rStart < rows
  • 0 <= cStart < cols

[Solution]

class Solution:

    def spiralMatrixIII(self, rows: int, cols: int, rStart: int, cStart: int) -> List[List[int]]:
        dx = [0, 1, 0, -1]
        dy = [1, 0, -1, 0]
        direction = 0
        distance = 0
        total_cells = rows * cols

        r, c = rStart, cStart
        ret = [[r,c]]
            
        while len(ret) < total_cells:
            if not direction % 2:
                distance += 1
            # move
            for _ in range(distance):
                r += dx[direction]
                c += dy[direction]
                if 0 <= r < rows and 0 <= c < cols:
                    ret.append([r,c])
                if len(ret) == total_cells:
                    return ret
            direction = (direction + 1) % 4
        return ret

 

 

What I Learn:

python supports double conditional operator in one condition statement~ (0<=r<rows)

'algo > leetcode' 카테고리의 다른 글

837. New 21 Game  (0) 2024.08.18
2101. Detonate the Maximum Bombs  (0) 2024.08.15
322. Coin Change  (0) 2024.08.11
70. Climbing Stairs  (0) 2024.08.11
2. Add Two Numbers  (0) 2024.08.10