Drill

ProblemsC++ › patterns

Read the floor plan in a spiral

hardpatternsGridsArraysC++

A stocktake walks a warehouse grid from the outside in, clockwise, so the counter never crosses their own path.

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.

Solve it in Python →

Where you start

std::vector<int> spiralWalk(std::vector<std::vector<int>> bays) {
    
}

Worked examples

CallResult
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;
}

The same problem in another language

More patterns problems in C++