GolangNote

Golang笔记

Golang 二维数组旋转

Permalink

二维数组旋转,类似2D图像作90度旋转

Go: 多维数组旋转
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
package main

import (
	"fmt"
)

func main() {
	matrix := [][]int{{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}
	fmt.Println(matrix)
	rotate(matrix)
	fmt.Println(matrix)
}

func rotate(matrix [][]int) {
	m := len(matrix)
	tmp := 0

	for i := 0; i < m/2; i++ {
		for j := i; j < m-1-i; j++ {
			tmp = matrix[i][j]
			matrix[i][j] = matrix[m-1-j][i]
			matrix[m-1-j][i] = matrix[m-1-i][m-1-j]
			matrix[m-1-i][m-1-j] = matrix[j][m-1-i]
			matrix[j][m-1-i] = tmp
		}
	}
}

输出:

plaintext: 旋转结果
1
2
[[1 2 3] [4 5 6] [7 8 9]]
[[7 4 1] [8 5 2] [9 6 3]]

本文网址: https://golangnote.com/topic/285.html 转摘请注明来源

Related articles

Write a Comment to "Golang 二维数组旋转"

Submit Comment Login
Based on Golang + fastHTTP + sdb | go1.22.3 Processed in 0ms