Walk a grid in a spiral
grid is a rectangle of numbers with m rows and n columns. Walk it in a spiral: start at the top-left cell, go right along the top row, down the right column, left along the bottom row and up the left column, then keep turning inward the same way until every cell has been visited exactly once.
Return the numbers in the order you visit them.
- Input
grid = [[4,9,2],[3,5,7],[8,1,6]]- Output
[4,9,2,7,6,1,8,3,5]
Along the top (4, 9, 2), down the right (7, 6), back along the bottom (1, 8), up the left (3), and the centre last (5).
- Input
grid = [[10,20,30,40],[50,60,70,80]]- Output
[10,20,30,40,80,70,60,50]
Two rows: the top left to right, then the bottom right to left.
- Input
grid = [[7],[8],[9]]- Output
[7,8,9]
A single column is walked straight down.
Limits
1 <= m, n <= 200-1000 <= grid[i][j] <= 1000
Hints
Hint 1
Keep four borders: the top row, bottom row, left column and right column still to be walked.
Hint 2
Walk one lap along the borders, then move every border one step inward. Watch the case where only one row or one column is left, so it is not walked twice.
Where this was reported
- Walmart, SDE on-campus interview, 2024 (GeeksforGeeks)
Our own problem on the task these candidates describe; the wording, examples and tests are InternDoor’s.
Run your code to check it on the examples. Submit runs every hidden test.
