我正在try 将矩阵顺时针旋转90°,特别是使用非就地旋转算法.我想出了这个代码:
func RotateClockWiseNIP(matrix [][]int) (out [][]int) {
// Create and populate a new out matrix full of zero
nullRow := []int{}
为 i := 0; i < len(matrix); i++ {
nullRow = append(nullRow, 0)
}
为 i := 0; i < len(matrix); i++ {
out = append(out, nullRow)
}
fmt.Println(out)
// Change values accordingly
为 row := 0; row < len(matrix); row++ {
为 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
}
其 idea 是将每一行作为列放置在新的矩阵中.例如,第一行将是最后一列,第二行将是倒数第二列,依此类推.
现在代码可以工作了,但并不像预期的那样.打印出矩阵[][]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{}
为 i := 0; i < len(matrix); i++ {
nullRow = append(nullRow, 0)
}
为 i := 0; i < len(matrix); i++ {
out = append(out, nullRow)
}
为
为 i := 0; i < len(matrix); i++ {
out = append(out, []int{})
为 j := 0; j < len(matrix); j++ {
out[i] = append(out[i], 0)
}
}
解决了问题.不过,我就不提这个问题了,因为我真的不能理解第一种方法的错误之处.