Drill

ProblemsGo › patterns

Read the floor plan in a spiral

hardpatternsGridsArraysGo

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>

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.

Solve it in Python →

Where you start

func spiralWalk(bays [][]int) []int {
	
}

Worked examples

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

The same problem in another language

More patterns problems in Go