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
std::vector<int> spiralWalk(std::vector<std::vector<int>> bays) {
}
Worked examples
| Call | Result |
|---|---|
spiralWalk(std::vector<std::vector<int>>{std::vector<int>{1, 2, 3}, std::vector<int>{4, 5, 6}, std::vector<int>{7, 8, 9}}) | std::vector<int>{1, 2, 3, 6, 9, 8, 7, 4, 5} |
spiralWalk(std::vector<std::vector<int>>{std::vector<int>{1, 2}, std::vector<int>{3, 4}}) | std::vector<int>{1, 2, 4, 3} |
spiralWalk(std::vector<std::vector<int>>{std::vector<int>{1, 2, 3}}) | std::vector<int>{1, 2, 3} |
spiralWalk(std::vector<std::vector<int>>{std::vector<int>{1}, std::vector<int>{2}, std::vector<int>{3}}) | std::vector<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++
std::vector<int> spiralWalk(std::vector<std::vector<int>> bays) {
std::vector<int> walk;
if (bays.empty()) return walk;
int top = 0, bottom = static_cast<int>(bays.size()) - 1;
int left = 0, right = static_cast<int>(bays[0].size()) - 1;
while (top <= bottom && left <= right) {
for (int c = left; c <= right; c++) walk.push_back(bays[top][c]);
top++;
for (int r = top; r <= bottom; r++) walk.push_back(bays[r][right]);
right--;
if (top <= bottom) {
for (int c = right; c >= left; c--) walk.push_back(bays[bottom][c]);
bottom--;
}
if (left <= right) {
for (int r = bottom; r >= top; r--) walk.push_back(bays[r][left]);
left++;
}
}
return walk;
}