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.
Examples
Example 1:
|
|
Example 2:
|
|
Similar Problems
Solution
Method 1 - Simulation
We know that we start from position [rStart, cStart]
, and we start in direction East, then we go to South, West and north and start the same process.
So, we can define directions:
|
|
We add [rStart, cStart]
to our answer, and go to east.
Then in each direction we take x
steps. Initially x = 1
, but then it increases by 1 ( - observe carefully - ) when we completed the steps in 2 directions. In eg. 2, we go from 1 → 2, and then 2 → 3, then our number steps increases to 2. Similarly, now we go to 3 → 5, and 5 → 7, then our number of steps increase to 3. So, we go from 7 → out of bounds (right of 9) and so on. So, each time we ran into 2 directions, we have to increase the number of steps. So, we can loop twice for the same number of steps, and increase our steps after that.
Also, when we have walked full x
steps, we change the direction as well.
So, now to the code.
Video Explanation
Here is the video explanation for solving the problem:
Code
|
|
|
|
Complexity
- ⏰ Time complexity:
O(row * cols)
- 🧺 Space complexity:
O(rows * cols)