在Go中旋转矩阵

5rgfhyps  于 2023-10-14  发布在  Go
关注(0)|答案(1)|浏览(159)

我正在尝试将矩阵顺时针旋转90°,特别是使用不到位的旋转算法。我想出了这个代码:

  1. func RotateClockWiseNIP(matrix [][]int) (out [][]int) {
  2. // Create and populate a new out matrix full of zero
  3. nullRow := []int{}
  4. for i := 0; i < len(matrix); i++ {
  5. nullRow = append(nullRow, 0)
  6. }
  7. for i := 0; i < len(matrix); i++ {
  8. out = append(out, nullRow)
  9. }
  10. fmt.Println(out)
  11. // Change values accordingly
  12. for row := 0; row < len(matrix); row++ {
  13. for c := 0; c < len(matrix); c++ {
  14. fmt.Printf("The matrix element %v %v goes to out element %v %v\n", row, c, c, len(matrix)-1-row)
  15. out[c][len(matrix)-1-row] = matrix[row][c]
  16. fmt.Println(out)
  17. }
  18. }
  19. return
  20. }

我们的想法是把每一行,并把它作为列在新的矩阵。例如,第一行是最后一列,第二行是倒数第二列,依此类推。现在代码可以工作了,但并不像预期的那样。打印出矩阵[][]int{{1,2},{3,4}的结果会给出:

  1. [[0 0] [0 0]]
  2. The matrix element 0 0 goes to out element 0 1
  3. [[0 1] [0 1]]
  4. The matrix element 0 1 goes to out element 1 1
  5. [[0 2] [0 2]]
  6. The matrix element 1 0 goes to out element 0 0
  7. [[3 2] [3 2]]
  8. The matrix element 1 1 goes to out element 1 0
  9. [[4 2] [4 2]]

你可以看到,每次赋值都在两行上重复,而不是只在out矩阵中的右边位置。有什么线索能解释为什么会这样吗?太感谢你了!

显然,问题出在第一部分。交换

  1. nullRow := []int{}
  2. for i := 0; i < len(matrix); i++ {
  3. nullRow = append(nullRow, 0)
  4. }
  5. for i := 0; i < len(matrix); i++ {
  6. out = append(out, nullRow)
  7. }

  1. for i := 0; i < len(matrix); i++ {
  2. out = append(out, []int{})
  3. for j := 0; j < len(matrix); j++ {
  4. out[i] = append(out[i], 0)
  5. }
  6. }

解决了问题我将留下这个问题,因为我真的不明白第一种方法有什么错。

cygmwpex

cygmwpex1#

在第一种方法中,将相同的切片nullRow附加到所有行。Slice具有带指针的底层值。所以所有的行都有相同的值。

相关问题