48-旋转图像

48-旋转图像

力扣48

https://leetcode-cn.com/problems/rotate-image/

所谓原地旋转,就是不能新建一个数组

思路1:计算某个点距离上下左右的坐标,一次循环翻转4个值

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
|- - - - - - - - - - - - - - - - -|
| ↑ |
| toTop |
| ↓ |
| ← toLeft → o ← - - toRight - - →|
| ↑ |
| | |
| toBottom |
| | |
| ↓ |
|- - - - - - - - - - - - - - - - -|

旋转过后

|- - - - - - - - - - - - - - - - -|
| ↑ |
| toLeft |
| ↓ |
| ← - - toBottom - - → o ← toTop →|
| ↑ |
| | |
| toRight |
| | |
| ↓ |
|- - - - - - - - - - - - - - - - -|
四个一周期
点a旋转后占了b的位置,b占了c的位置,c占了d的位置,d一定会回到a的位置

用个变量记录下来,或者python的话可以直接a, b, c, d = b, c, d, a

1
2
3
4
5
6
7
8
9
10
11
12
13
14
public void rotate(int[][] matrix) {
int row = (matrix.length % 2 == 0) ? (matrix.length / 2) : (matrix.length / 2 + 1);
for (int i = 0; i < row; i++) {
for (int j = 0; j < matrix[0].length / 2; j++) {
int toTop = i, toRight = matrix[0].length - j - 1, toBottom= matrix.length - i - 1, toLeft = j;
//四个旋转坐标交换
int temp = matrix[toTop][toLeft];
matrix[toTop][toLeft] = matrix[toRight][toTop];
matrix[toRight][toTop] = matrix[toBottom][toRight];
matrix[toBottom][toRight] = matrix[toLeft][toBottom];
matrix[toLeft][toBottom] = temp;
}
}
}

思路2:转置+对称

顺时针:转置+左右对称

180°:上下对称+左右对称

逆时针:转置+上下对称

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
public void rotate2(int[][] matrix) {
//矩阵转置
for(int i=0;i<matrix.length;i++){
for(int j=0;j<i;j++){
int tem=matrix[j][i];
matrix[j][i]=matrix[i][j];
matrix[i][j]=tem;
}
}

//左右翻转
for(int i=0;i<matrix.length;i++){
for(int j = 0; j < matrix.length / 2; j++){
int tem = matrix[i][matrix.length - 1 - j];
matrix[i][matrix.length - 1 - j] = matrix[i][j];
matrix[i][j] = tem;
}
}
}

其他题目点击这里

Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×