# 构建数组

n=5时如下:

``````0   0   0   0   5
0   0   0   6   4
0   0   7   14  3
0   8   15  13  2
9   10  11  12  1
``````

n=3时如下:

``````0   0   3
0   4   2
5   6   1
``````

``````package main

import (
"fmt"
)

func main() {
/*
输入n，输出方阵，
n=6时如下
0   0   0   0   0   6
0   0   0   0   7   5
0   0   0   8   18  4
0   0   9   19  17  3
0   10  20  21  16  2
11  12  13  14  15  1
n=3时如下
0   0   3
0   4   2
5   6   1
*/
n := 6
res := getres(n)
for i := 0; i < len(res); i++ {
fmt.Println(res[i])
}
}

func getres(n int) [][]int {
matrix := make([][]int, n)
for i := 0; i < n; i++ {
matrix[i] = make([]int, n)
}
direction := 0
idx := 1
left := 0
right := n - 1

low := 0
high := n - 1

final := n * (n + 1) / 2
fmt.Println(final)
for idx <= final {
switch direction % 3 {
case 0: //下->上
for i := high; i >= low; i-- {
matrix[i][right] = idx
idx += 1
}
right -= 1
low += 1
case 1: //右上->左下
for i, j := low, right; i <= high && j >= left; i, j = i+1, j-1 {
matrix[i][j] = idx
idx += 1
}
low += 1
left += 1
case 2: //左->右
for j := left; j <= right; j++ {
matrix[high][j] = idx
idx += 1
}
high -= 1
left += 1
}
direction += 1
}
return matrix
}

``````

output:

``````[0  0   0  0  0  6]
[0  0   0  0  7  5]
[0  0   0  8  18 4]
[0  0   9  19 17 3]
[0  10  20 21 16 2]
[11 12  13 14 15 1]
``````