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

66 lines
1.2 KiB

package cap3
// Ex21 螺旋阵
func Ex21(n int) [][]int {
matrix := _makeMatrix(n)
// 逐层往里填充
num := 1
for layer := 0; layer < n/2; layer++ {
// 方阵左边
for i := layer; i < n-layer; i++ {
matrix[i][layer] = num
num++
}
// 方阵下边
for i := layer + 1; i < n-layer; i++ {
matrix[n-layer-1][i] = num
num++
}
// 方阵右边
for i := n - layer - 2; i >= layer; i-- {
matrix[i][n-layer-1] = num
num++
}
// 方阵上边
for i := n - layer - 2; i > layer; i-- {
matrix[layer][i] = num
num++
}
}
// 奇数阶中间位置需要手动设置
if n%2 != 0 {
matrix[n/2][n/2] = n * n
}
return matrix
}
func Ex21type2(n int) [][]int {
matrix := _makeMatrix(n + 10)
row, col, t := 0, 0, 1
for i := 0; i < n*n; {
for j := 0; j < 2*n; j++ {
i++
matrix[row][col] = i
switch (j + 1) / (n + 1) {
case 0:
row += t
case 1:
col += t
}
}
n--
t = -t
}
return matrix
}