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.
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;}}}