You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
lavos/cap3/work5.go

39 lines
846 B

package cap3
func Work5(n int) [][]int {
matrix := make([][]int, n)
for i := range matrix {
matrix[i] = make([]int, n)
}
// 逐层往里填充
for layer := 0; layer < n/2; layer++ {
// 方阵上边
for i := layer; i < n-layer; i++ {
matrix[layer][i] = layer + 1
}
// 方阵右边
for i := layer + 1; i < n-layer; i++ {
matrix[i][n-layer-1] = layer + 1
}
// 方阵下边
for i := n - layer - 2; i >= layer; i-- {
matrix[n-layer-1][i] = layer + 1
}
// 方阵左边
for i := n - layer - 2; i > layer; i-- {
matrix[i][layer] = layer + 1
}
}
// 奇数阶中间位置需要手动设置
if n%2 != 0 {
matrix[n/2][n/2] = n/2 + 1
}
return matrix
}