Read the floor plan in a spiral
A stocktake walks a warehouse grid from the outside in, clockwise, so the counter never crosses their own path.
- Start at the top left and move right along the top row.
- Then down the right edge, back along the bottom, up the left, and inwards.
- Every cell appears exactly once.
- An empty grid gives an empty walk.
SpiralWalk(bays: list<list<int>>) → list<int>
C# needs a compiler and Drill does not host one yet, so this page is the reference rather than an exercise: the problem, worked examples, and the solution in full. To type it out, the same problem runs in Python.
Where you start
public List<int> SpiralWalk(List<List<int>> bays) {
}
Worked examples
| Call | Result |
|---|---|
SpiralWalk(new List<List<int>> { new List<int> { 1, 2, 3 }, new List<int> { 4, 5, 6 }, new List<int> { 7, 8, 9 } }) | new List<int> { 1, 2, 3, 6, 9, 8, 7, 4, 5 } |
SpiralWalk(new List<List<int>> { new List<int> { 1, 2 }, new List<int> { 3, 4 } }) | new List<int> { 1, 2, 4, 3 } |
SpiralWalk(new List<List<int>> { new List<int> { 1, 2, 3 } }) | new List<int> { 1, 2, 3 } |
SpiralWalk(new List<List<int>> { new List<int> { 1 }, new List<int> { 2 }, new List<int> { 3 } }) | new List<int> { 1, 2, 3 } |
Hint
Track four edges — top, bottom, left, right. Walk one of them, then pull that edge in, and stop when they cross.
Reference solution in C#
public List<int> SpiralWalk(List<List<int>> bays) {
var walk = new List<int>();
if (bays.Count == 0) return walk;
int top = 0, bottom = bays.Count - 1, left = 0, right = bays[0].Count - 1;
while (top <= bottom && left <= right) {
for (int c = left; c <= right; c++) walk.Add(bays[top][c]);
top++;
for (int r = top; r <= bottom; r++) walk.Add(bays[r][right]);
right--;
if (top <= bottom) {
for (int c = right; c >= left; c--) walk.Add(bays[bottom][c]);
bottom--;
}
if (left <= right) {
for (int r = bottom; r >= top; r--) walk.Add(bays[r][left]);
left++;
}
}
return walk;
}