885. Spiral Matrix III
All prompts are owned by LeetCode. To view the prompt, click the title link above.
First completed : August 08, 2024
Last updated : August 08, 2024
Related Topics : Array, Matrix, Simulation
Acceptance Rate : 84.66 %
Observing the samples, the distance of each "side" travelled follows the order of 1, 1, 2, 2, 3, 3, 4, 4, ... etc. I.e. we repeat a side length then increment. This makes sense as it follows whether we're traversing the height or width of the current "square." It is possible to further optimize this by "skipping" the out-of-bounds portions but this optimization isn't necessary for this medium question. ```
class Solution:
def spiralMatrixIII(self, rows: int, cols: int, rStart: int, cStart: int) -> List[List[int]]:
output = [[rStart, cStart]]
distance = 1 # current side length
direction = 0 # 0=r, 1=d, 2=l, 3=u
twice = False
while len(output) < rows * cols :
for i in range(1, distance + 1) :
match direction % 4 :
case 0 :
cStart += 1
case 1 :
rStart += 1
case 2 :
cStart -= 1
case 3 :
rStart -= 1
if not (0 <= cStart < cols) or not (0 <= rStart < rows) :
continue
output.append([rStart, cStart])
direction += 1
twice = not twice
if not twice :
distance += 1
return output