package main
import "fmt"
func PrintMatrixInSpiralForm(matrix [][]int) {
if matrix == nil || len(matrix) == 0 {
return
}
top, bottom := 0, len(matrix)-1
left, right := 0, len(matrix[0])-1
for {
if left > right {
break
}
// top row
for i := left; i <= right; i++ {
fmt.Print(matrix[top][i], " ")
}
fmt.Println()
top++ // next row
if top > bottom {
break
}
// right column
for i := top; i <= bottom; i++ {
fmt.Print(matrix[i][right], " ")
}
fmt.Println()
right-- // previous column
if left > right {
break
}
// bottom row
for i := right; i >= left; i-- {
fmt.Print(matrix[bottom][i], " ")
}
fmt.Println()
bottom-- // previous row
if top > bottom {
break
}
// left column
for i := bottom; i >= top; i-- {
fmt.Print(matrix[i][left], " ")
}
fmt.Println()
left++ // next column
}
}
func main() {
matrix := [][]int{
{ 1, 2, 3, 4},
{ 5, 6, 7, 8},
{ 9, 10, 11, 12},
{13, 14, 15, 16},
}
PrintMatrixInSpiralForm(matrix)
}
/*
run:
1 2 3 4
8 12 16
15 14 13
9 5
6 7
11
10
*/