我正在尝试将矩阵顺时针旋转90°,特别是使用不到位的旋转算法。我想出了这个代码:
func RotateClockWiseNIP(matrix [][]int) (out [][]int) {
// Create and populate a new out matrix full of zero
nullRow := []int{}
for i := 0; i < len(matrix); i++ {
nullRow = append(nullRow, 0)
}
for i := 0; i < len(matrix); i++ {
out = append(out, nullRow)
}
fmt.Println(out)
// Change values accordingly
for row := 0; row < len(matrix); row++ {
for c := 0; c < len(matrix); c++ {
fmt.Printf("The matrix element %v %v goes to out element %v %v\n", row, c, c, len(matrix)-1-row)
out[c][len(matrix)-1-row] = matrix[row][c]
fmt.Println(out)
}
}
return
}
我们的想法是把每一行,并把它作为列在新的矩阵。例如,第一行是最后一列,第二行是倒数第二列,依此类推。现在代码可以工作了,但并不像预期的那样。打印出矩阵[][]int{{1,2},{3,4}
的结果会给出:
[[0 0] [0 0]]
The matrix element 0 0 goes to out element 0 1
[[0 1] [0 1]]
The matrix element 0 1 goes to out element 1 1
[[0 2] [0 2]]
The matrix element 1 0 goes to out element 0 0
[[3 2] [3 2]]
The matrix element 1 1 goes to out element 1 0
[[4 2] [4 2]]
你可以看到,每次赋值都在两行上重复,而不是只在out
矩阵中的右边位置。有什么线索能解释为什么会这样吗?太感谢你了!
显然,问题出在第一部分。交换
nullRow := []int{}
for i := 0; i < len(matrix); i++ {
nullRow = append(nullRow, 0)
}
for i := 0; i < len(matrix); i++ {
out = append(out, nullRow)
}
为
for i := 0; i < len(matrix); i++ {
out = append(out, []int{})
for j := 0; j < len(matrix); j++ {
out[i] = append(out[i], 0)
}
}
解决了问题我将留下这个问题,因为我真的不明白第一种方法有什么错。
1条答案
按热度按时间cygmwpex1#
在第一种方法中,将相同的切片
nullRow
附加到所有行。Slice具有带指针的底层值。所以所有的行都有相同的值。