抱歉,您的浏览器无法访问本站
本页面需要浏览器支持(启用)JavaScript
了解详情 >

矩阵旋转操作是为了将其它三个方向的移动都转换为向上的移动操作。向下、向左、向右转换为向上操作时,数组需要进行翻转操作参考正文代码。

执行代码

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
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
package main

import "fmt"

type g2048 [4][4]int

func (t *g2048) MirrorV() {
tn := new(g2048)
for i, line := range t {
for j, num := range line {
tn[len(t)-i-1][j] = num
}
}
*t = *tn
}

func (t *g2048) Right90() {
tn := new(g2048)
for i, line := range t {
for j, num := range line {
tn[j][len(t)-i-1] = num
}
}
*t = *tn
}

func (t *g2048) Left90() {
tn := new(g2048)
for i, line := range t {
for j, num := range line {
tn[len(line)-j-1][i] = num
}
}
*t = *tn
}

func (g *g2048) R90() {
tn := new(g2048)
for x, line := range g {
for y, _ := range line {
tn[x][y] = g[len(line)-1-y][x]
}
}
*g = *tn

}

func (t *g2048) Right180() {
tn := new(g2048)
for i, line := range t {
for j, num := range line {
tn[len(line)-i-1][len(line)-j-1] = num
}
}
*t = *tn
}

func (t *g2048) Print() {
for _, line := range t {
for _, number := range line {
fmt.Printf("%2d ", number)
}
fmt.Println()
}
fmt.Println()
tn := g2048{{1, 2, 3, 4}, {5, 8}, {9, 10, 11}, {13, 14, 16}}
*t = tn

}

func main() {
fmt.Println("origin")
t := g2048{{1, 2, 3, 4}, {5, 8}, {9, 10, 11}, {13, 14, 16}}
t.Print()
fmt.Println("mirror")
t.MirrorV()
t.Print()
fmt.Println("Left90")
t.Left90()
t.Print()
fmt.Println("Right90")
t.R90()
t.Print()
fmt.Println("Right180")
t.Right180()
t.Print()
}

注意:创建源文件 martix_rorate.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
29
origin
1 2 3 4
5 8 0 0
9 10 11 0
13 14 16 0

mirror
13 14 16 0
9 10 11 0
5 8 0 0
1 2 3 4

Left90
4 0 0 0
3 0 11 16
2 8 10 14
1 5 9 13

Right90
13 9 5 1
14 10 8 2
16 11 0 3
0 0 0 4

Right180
0 16 14 13
0 11 10 9
0 0 8 5
4 3 2 1

注意:执行 go run martix_rorate.go 后,输出如上。

评论