// Package spiralmatrix creates spiral matrices.
package spiralmatrix
type direction int
const (
right direction = iota
down
left
up
)
type matrix struct {
d direction
min int
max int
row int
column int
}
// SpiralMatrix returns slices of a spiral matrix.
func SpiralMatrix(size int) [][]int {
ret := make([][]int, size)
for i := range ret {
ret[i] = make([]int, size)
}
m := matrix{max: size - 1}
for i := 1; i <= size*size; i++ {
ret[m.row][m.column] = i
m.next()
if m.row == m.min && m.column == m.min && i != 1 {
// we reached top left corner, going to the inner circle
m.min++
m.max--
m.row++
m.column++
}
}
return ret
}
func (m *matrix) direction() {
switch {
case m.d == right && m.column+1 <= m.max:
// keep right
case m.d == down && m.row+1 <= m.max:
// keep down
case m.d == left && m.column-1 >= m.min:
// keep left
case m.d == up && m.row-1 >= m.min:
// keep up
default:
// go to next direction
m.d = (m.d + 1) % 4
}
}
func (m *matrix) next() {
m.direction()
switch m.d {
case right:
m.column++
case down:
m.row++
case left:
m.column--
case up:
m.row--
}
}