版權聲明:轉載請聯系本人,感謝配合!本站位址: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;
}