48. Rotate Image
Description
描述:https://leetcode.com/problems/rotate-image/description/
题意:将一个矩阵(二维数组)顺时针旋转90度,不能分配额外的二维空间。
Solution: (Java)
class Solution {
public void rotate(int[][] matrix) {
int start_index = 0;
int n = matrix[0].length;
int j_max = n - 2;
int i_max = n/2 - 1;
int temp, current, temp_i, temp_j, temp_k;
for (int i = 0; i <= i_max; i++) {
for (int j = start_index; j <= j_max; j++) {
current = matrix[i][j];
temp_i = i;
temp_j = j;
for (int k = 0; k < 4; k++) {
temp = matrix[temp_j][n-1-temp_i];
matrix[temp_j][n-1-temp_i] = current;
current = temp;
temp_k = temp_i;
temp_i = temp_j;
temp_j = n-1-temp_k;
}
}
start_index = start_index + 1;
j_max = j_max - 1;
}
}
}
思路
- 找到每个坐标的变换规律即可,即
matrix[i][j]
的值旋转90度之后,会变换到matrix[j][n-1-i]
这个位置; - 每个位置会与其他3个值互相影响,所以中间有个4次的循环;
- 其他要注意的就是编程的处理了,保证每个位置只遍历一遍,注意循环的边界变化。