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/work3.go

45 lines
939 B

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