FunctionRacerProblemsRace

Spiral Out From a Cell

MediumGridsPython, JavaScript, TypeScript, Java, C++

You stand on the cell in row row and column col of a grid with rows rows and cols columns, facing up (towards row 0). You walk an outward spiral that turns left, that is counterclockwise: 1 step up, 1 step left, 2 steps down, 2 steps right, 3 steps up, 3 steps left, 4 steps down, and so on, turning left after every stretch and making the stretches one step longer after every second turn. The walk may leave the grid and come back into it later; only the cells inside the grid count. Return the positions [row, col] of all the cells of the grid in the order you first stand on them, starting with the start cell, and stop as soon as every cell has been listed.

Example 1

rows 3
cols 3
row 1
col 1
returns [[1,1],[0,1],[0,0],[1,0],[2,0],[2,1],[2,2],[1,2],[0,2]]

From the centre you step up to [0, 1], left to [0, 0], down twice to [2, 0], right twice to [2, 2], and the first two steps of the next upward stretch reach the last two cells.

Example 2

rows 1
cols 4
row 0
col 1
returns [[0,1],[0,0],[0,2],[0,3]]

Most of this walk is outside the single row. It comes back into the row at column 0 on the first downward stretch, at column 2 on the first long upward stretch, and at column 3 much later.

Constraints

Race itor take your time

Write it in your browser, against the clock. The model solution, stepped through line by line, comes after.

More Grids problems