版权声明:转载请联系本人,感谢配合!本站地址:http://blog.csdn.net/nomasp https://blog.csdn.net/NoMasp/article/details/52436170
翻译
给定一个n∗n的2D矩阵表示一个图像。
顺时针旋转90度。
跟进:
你可以就地完成它吗?
原文
You are given an n x n 2D matrix representing an image.
Rotate the image by 90 degrees (clockwise).
Follow up:
Could you do this in-place?
分析
尊重原创,一个很好的思路~
public void rotate(int[][] matrix) {
for (int i = 0; i < matrix.length / 2; i++) {
swapArray(matrix, i, matrix.length - i);
}
for (int i = 0; i < matrix.length; ++i) {
for (int j = i + 1; j < matrix[i].length; ++j) {
swapValue(matrix, i, j);
}
}
}
void swapArray(int[][] matrix, int a, int b) {
int[] tmp = matrix[a];
matrix[a] = matrix[b];
matrix[b] = tmp;
}
void swapValue(int[][] matrix, int i, int j) {
int tmp = matrix[i][j];
matrix[i][j] = matrix[j][i];
matrix[j][i] = tmp;
}