You are given an n x n 2D matrix representing an image, rotate the image by 90 degrees (clockwise).
You have to rotate the image in-place, which means you have to modify the input 2D matrix directly. DO NOT allocate another 2D matrix and do the rotation.
The first idea is a new matrix with \(\textit{matrix}[j][n-1-i] \gets \textit{matrix}[i][j]\). Correct, \(O(n^2)\) time and space. \(n \le 20\) fits, but the problem requires in-place.
The extra matrix is the bottleneck. A \(90^\circ\) clockwise turn factors into two in-place flips: reverse upside-down, then transpose across the main diagonal.
\((i, j)\) goes to \((n-1-i, j)\), then to \((j, n-1-i)\) — the target. Two rounds of swaps, \(O(1)\) extra space.
According to the problem requirements, we need to rotate \(\text{matrix}[i][j]\) to \(\text{matrix}[j][n - i - 1]\).
We can first flip the matrix upside down, i.e., swap \(\text{matrix}[i][j]\) with \(\text{matrix}[n - i - 1][j]\), and then flip the matrix along the main diagonal, i.e., swap \(\text{matrix}[i][j]\) with \(\text{matrix}[j][i]\). This way, we can rotate \(\text{matrix}[i][j]\) to \(\text{matrix}[j][n - i - 1]\).
The time complexity is \(O(n^2)\), where \(n\) is the side length of the matrix. The space complexity is \(O(1)\).
/** Do not return anything, modify matrix in-place instead. */functionrotate(matrix:number[][]):void{matrix.reverse();for(leti=0;i<matrix.length;++i){for(letj=0;j<i;++j){constt=matrix[i][j];matrix[i][j]=matrix[j][i];matrix[j][i]=t;}}}