GolangNote

Golang笔记

Golang 二维数组旋转

Permalink

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

Golang 二维数组旋转

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
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]]

Related articles

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

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