Fork me on GitHub

LeetCode-48:旋转图像

本题为LeetCode中的第48道题,今天咱们就来看看这道题,再顺便提一下Java中数组的深浅拷贝

这道题是我没做出来,偷懒开辟了其他数组,不过还给过了,就在这贴上吧


给定一个 n × n 的二维矩阵表示一个图像。

将图像顺时针旋转 90 度。

说明

你必须在原地旋转图像,这意味着你需要直接修改输入的二维矩阵。请不要使用另一个矩阵来旋转图像。

示例 1:

1
2
3
4
5
6
7
8
9
10
11
12
13
给定 matrix = 
[
[1,2,3],
[4,5,6],
[7,8,9]
],

原地旋转输入矩阵,使其变为:
[
[7,4,1],
[8,5,2],
[9,6,3]
]

示例 2:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
给定 matrix =
[
[ 5, 1, 9,11],
[ 2, 4, 8,10],
[13, 3, 6, 7],
[15,14,12,16]
],

原地旋转输入矩阵,使其变为:
[
[15,13, 2, 5],
[14, 3, 4, 1],
[12, 6, 8, 9],
[16, 7,10,11]
]

大概说一下我的思路,像这种题一般都有规律,我们只需要找出数组下标转移的规律即可解题:

咱们从示例一来分析

1
2
3
4
5
6
7
8
9
[0,0]————>[0,2]
[0,1]————>[1,2]
[0,2]————>[2,2]
[1,0]————>[0,1]
[1,1]————>[1,1]
[1,2]————>[2,1]
[2,0]————>[0,0]
[2,1]————>[1,0]
[2,2]————>[2,0]

来看一段侧四代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
@Test
public void test(){
int i = 0;
int count = 0;
int length = 3;
int j = length;
int count_j = 0;
while(count<9){

i = i%3;
if(count_j%length==0){
j--;
}
System.out.println("["+i+","+j+"]");

i++;
count++;
count_j++;
}
}

这段代码就计算出了后面的坐标

再来看看我的完整代码:

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
/**
* @author RickYinPeng
* @ClassName Rotating_image
* @Description LeetCode中第48道题
* @date 2018/10/10/22:55
*
* 题目名称:旋转图像
*/
public class Rotating_image {

public static void main(String[] args) {
int[][] num = {
{1,2,3},
{4,5,6},
{7,8,9}
};
rotate(num);
for(int i = 0;i<num.length;i++){
for(int j = 0;j<num.length;j++){
System.out.print(num[i][j]+",");
}
System.out.println();
}

}

public static void rotate(int[][] matrix) {
int length = matrix.length;
int i = 0;

int j = length;
int count_j = 0;
int[][] matrixTemp = new int[length][length];
for(int f = 0;f<matrix.length;f++) {
matrixTemp[f] = matrix[f].clone();
}
int a = 0;
for(int x =0;x<matrixTemp.length;x++) {
for(int y = 0;y<matrix.length;y++) {
a = matrixTemp[x][y];

//计算i的值
i = i % 3;

//计算j的值
if (count_j % length == 0) {
j--;
}
System.out.println(a);
System.out.println("["+i+","+j+"]");
matrix[i][j] = a;


i++;
count_j++;
}
}
}
}

这里还了解了Java数组的深浅拷贝,这个后面我会专门写一篇的,这里就不说了