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

67 lines
1.2 KiB

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