Rotate a Matrix
Rotate a Matrix
Flip the matrix upside down. Then mirror it along the diagonal where i and j swap places.
void rotate(vector<vector<int>>& mat) {
reverse(mat.begin(), mat.end());
for(int i=0;i<mat.size();++i)
for(int j=i+1;j<mat[0].size();++j)
swap(mat[i][j], mat[j][i]);
}This works because rotation equals reversal plus transposition. The first step flips everything vertically. The second step swaps elements across the main diagonal.
The code runs in O(n²) time. It uses constant extra space since all operations happen in place.
#array