[Leetcode] 0885. Spiral Matrix III

Explore diverse LeetCode solutions in Python, C++, JavaScript, SQL, and TypeScript. Ideal for interview prep, learning, and code practice in multiple programming languages. Github Repo Link

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.

 

內容目錄

Python

				
					# time complexity: O(n^2)
# space complexity: O(n^2)
from typing import List


class Solution:
    def spiralMatrixIII(self, rows: int, cols: int, rStart: int, cStart: int) -> List[List[int]]:
        dirMap = [[0, 1], [1, 0], [0, -1], [-1, 0]]
        traverse = []
        direction = 0
        step = 1
        while len(traverse) < rows * cols:
            for _ in range(2):
                for _ in range(step):
                    if (rStart < rows and cStart < cols and rStart >= 0 and cStart >= 0):
                        traverse.append([rStart, cStart])
                    rStart += dirMap[direction][0]
                    cStart += dirMap[direction][1]
                direction = (direction + 1) % 4
            step += 1
        return traverse


rows = 5
cols = 6
rStart = 1
cStart = 4
print(Solution().spiralMatrixIII(rows, cols, rStart, cStart))
				
			
zh_TW繁體中文