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>
Go 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
func spiralWalk(bays [][]int) []int {
}
Worked examples
| Call | Result |
|---|---|
spiralWalk([][]int{[]int{1, 2, 3}, []int{4, 5, 6}, []int{7, 8, 9}}) | []int{1, 2, 3, 6, 9, 8, 7, 4, 5} |
spiralWalk([][]int{[]int{1, 2}, []int{3, 4}}) | []int{1, 2, 4, 3} |
spiralWalk([][]int{[]int{1, 2, 3}}) | []int{1, 2, 3} |
spiralWalk([][]int{[]int{1}, []int{2}, []int{3}}) | []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 Go
func spiralWalk(bays [][]int) []int {
walk := []int{}
if len(bays) == 0 {
return walk
}
top, bottom := 0, len(bays)-1
left, right := 0, len(bays[0])-1
for top <= bottom && left <= right {
for c := left; c <= right; c++ {
walk = append(walk, bays[top][c])
}
top++
for r := top; r <= bottom; r++ {
walk = append(walk, bays[r][right])
}
right--
if top <= bottom {
for c := right; c >= left; c-- {
walk = append(walk, bays[bottom][c])
}
bottom--
}
if left <= right {
for r := bottom; r >= top; r-- {
walk = append(walk, bays[r][left])
}
left++
}
}
return walk
}