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>
Java 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
List<Integer> spiralWalk(List<List<Integer>> bays) {
}
Worked examples
| Call | Result |
|---|---|
spiralWalk(Main.<List<Integer>>ls(Main.<Integer>ls(1, 2, 3), Main.<Integer>ls(4, 5, 6), Main.<Integer>ls(7, 8, 9))) | Main.<Integer>ls(1, 2, 3, 6, 9, 8, 7, 4, 5) |
spiralWalk(Main.<List<Integer>>ls(Main.<Integer>ls(1, 2), Main.<Integer>ls(3, 4))) | Main.<Integer>ls(1, 2, 4, 3) |
spiralWalk(Main.<List<Integer>>ls(Main.<Integer>ls(1, 2, 3))) | Main.<Integer>ls(1, 2, 3) |
spiralWalk(Main.<List<Integer>>ls(Main.<Integer>ls(1), Main.<Integer>ls(2), Main.<Integer>ls(3))) | Main.<Integer>ls(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 Java
List<Integer> spiralWalk(List<List<Integer>> bays) {
List<Integer> walk = new ArrayList<>();
if (bays.isEmpty()) return walk;
int top = 0, bottom = bays.size() - 1, left = 0, right = bays.get(0).size() - 1;
while (top <= bottom && left <= right) {
for (int c = left; c <= right; c++) walk.add(bays.get(top).get(c));
top++;
for (int r = top; r <= bottom; r++) walk.add(bays.get(r).get(right));
right--;
if (top <= bottom) {
for (int c = right; c >= left; c--) walk.add(bays.get(bottom).get(c));
bottom--;
}
if (left <= right) {
for (int r = bottom; r >= top; r--) walk.add(bays.get(r).get(left));
left++;
}
}
return walk;
}