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

public List<int> SpiralWalk(List<List<int>> bays) {
    
}

Worked examples

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

The same problem in another language

More patterns problems in C#