绘制2D矩阵,以螺旋格式打印给定矩阵的所有元素。给定一个数字n,使用O(1) 空间顺时针方向打印n x n螺旋矩阵(从1到n x n的数字)。

实现代码:

package main
  
import (
    "fmt"
)
  
func spiral(n int) []int {
    left, top, right, bottom := 0, 0, n-1, n-1
    sz := n * n
    s := make([]int, sz)
    i := 0
    for left < right {
        // work right, along top
        for c := left; c <= right; c++ {
            s[top*n+c] = i
            i++
        }
        top++
        // work down right side
        for r := top; r <= bottom; r++ {
            s[r*n+right] = i
            i++
        }
        right--
        if top == bottom {
            break
        }
        // work left, along bottom
        for c := right; c >= left; c-- {
            s[bottom*n+c] = i
            i++
        }
        bottom--
        // work up left side
        for r := bottom; r >= top; r-- {
            s[r*n+left] = i
            i++
        }
        left++
    }
    // center (last) element
    s[top*n+left] = i
  
    return s
}
  
func main() {
    num := 5
    len := 2
    for i, draw := range spiral(num) {
        fmt.Printf("%*d ", len, draw)
        if i%num == num-1 {
            fmt.Println("")
        }
    }
}

输出:

0  1  2  3  4 
15 16 17 18  5 
14 23 24 19  6 
13 22 21 20  7 
12 11 10  9  8