You are given R
rows and C
columns representing a matrix. Initially, you start from the cell (rStart, cStart)
. Your task is to return a list of coordinates representing the cells in the order you visit them in a spiral order.
Example:
Input: R = 1, C = 4, rStart = 0, cStart = 0
Output: [[0,0],[0,1],[0,2],[0,3]]
Constraints:
(rStart, cStart)
.R * C
coordinates.def spiralMatrixIII(R, C, rStart, cStart):
# Direction vectors for moving right, down, left, and up
directions = [(0, 1), (1, 0), (0, -1), (-1, 0)]
result = []
x, y = rStart, cStart
steps = 1
result.append([x, y])
if R * C == 1: # Edge case where the matrix is 1x1
return result
while len(result) < R * C:
for direction in directions:
for _ in range(steps):
x += direction[0]
y += direction[1]
if 0 <= x < R and 0 <= y < C:
result.append([x, y])
if direction == directions[1] or direction == directions[3]:
steps += 1
return result
This ensures an optimal traversal while guaranteeing that the spiral order is maintained and compliance with matrix boundaries is enforced.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?