https://leetcode.com/problems/rotate-image/discuss/18872/A-common-method-to-rotate-the-image

这个题用 正常的做法写一遍, 因为面试的时候, 这样是正常人的理解

https://www.youtube.com/watch?v=9ryIfj5DohI&t=386s



Given input matrix =
[
[ 5, 1, 9,11],
[ 2, 4, 8,10],
[13, 3, 6, 7],
[15,14,12,16]
],
rotate the input matrix in-place such that it becomes:
[
[15,13, 2, 5],
[14, 3, 4, 1],
[12, 6, 8, 9],
[16, 7,10,11]
]


/*
* clockwise rotate
* first reverse up to down, then swap the symmetry
* 1 2 3 7 8 9 7 4 1
* 4 5 6 => 4 5 6 => 8 5 2
* 7 8 9 1 2 3 9 6 3
*/

Solution 1 : normal way

class Solution {
public void rotate(int[][] matrix) {
if(matrix == null || matrix.length == 0) return;
int n = matrix.length;
int top = 0;
int bottom = n - 1;
int left = 0;
int right = n - 1;
while(n > 1){
for(int i = 0; i < n - 1; i++){
int tmp = matrix[top][left + i];
matrix[top][left + i] = matrix[bottom - i][left];
matrix[bottom - i][left] = matrix[bottom][right - i];
matrix[bottom][right - i] = matrix[top + i][right];
matrix[top + i][right] = tmp;
}
top++;
bottom--;
left++;
right--;
n -= 2;
}

}
}






Solution 2 : with trick

Swap the first row with the last row, swap the second row with the second row from bottom
Until there is nothing left in the middle

And then swap elements diagonally except the elements on the diagonal line


class Solution {
public void rotate(int[][] matrix) {
boolean[][] visited = new boolean[matrix.length][matrix[0].length];
// swap the bottom rows and the top rows except the ones in the middle
for(int i = 0; i < matrix.length / 2; i++){
for(int j = 0; j < matrix[0].length; j++){
// element on the top row : row is i, col is j
// element on the bottom row : row is matrix.length - 1 - i
int tmp = matrix[matrix.length - 1 - i][j];
matrix[matrix.length - 1 - i][j] = matrix[i][j];
matrix[i][j] = tmp;
}
}
// swap diagonally
for(int i = 0; i < matrix.length; i++){
for(int j = 0; j < matrix[0].length; j++){
if(i == j || visited[i][j]){
continue;
}
int tmp = matrix[i][j];
matrix[i][j] = matrix[j][i];
matrix[j][i] = tmp;
visited[i][j] = true;
visited[j][i] = true;
}
}
}
}






// other’s code , didn’t use boolean[][] visited ? How?
https://leetcode.com/problems/rotate-image/discuss/18879/AC-Java-in-place-solution-with-explanation-Easy-to-understand.