Given a matrix, clockwise rotate elements in it.
Examples:
Input
1 2 3
4 5 6
7 8 9
Output:
4 1 2
7 5 3
8 9 6
For 4*4 matrix
Input:
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16
Output:
5 1 2 3
9 10 6 4
13 11 7 8
14 15 16 12
The idea is to use loops similar to the program for printing a matrix in spiral form. One by one rotate all rings of elements, starting from the outermost. To rotate a ring, we need to do following.
1) Move elements of top row.
2) Move elements of last column.
3) Move elements of bottom row.
4) Move elements of first column.
Repeat above steps for inner ring while there is an inner ring.
Below is the implementation of above idea. Thanks to Gaurav Ahirwar for suggesting below solution.
Javascript
<script>
let R = 4;
let C = 4;
function rotatematrix(m, n, mat)
{
let row = 0, col = 0;
let prev, curr;
while (row < m && col < n)
{
if (row + 1 == m || col + 1 == n)
break ;
prev = mat[row + 1][col];
for (let i = col; i < n; i++)
{
curr = mat[row][i];
mat[row][i] = prev;
prev = curr;
}
row++;
for (let i = row; i < m; i++)
{
curr = mat[i][n - 1];
mat[i][n - 1] = prev;
prev = curr;
}
n--;
if (row < m)
{
for (let i = n - 1; i >= col; i--)
{
curr = mat[m - 1][i];
mat[m - 1][i] = prev;
prev = curr;
}
}
m--;
if (col < n)
{
for (let i = m - 1; i >= row; i--)
{
curr = mat[i][col];
mat[i][col] = prev;
prev = curr;
}
}
col++;
}
for (let i = 0; i < R; i++)
{
for (let j = 0; j < C; j++)
document.write( mat[i][j] + " " );
document.write( "<br>" );
}
}
let a = [ [ 1, 2, 3, 4 ],
[ 5, 6, 7, 8 ],
[ 9, 10, 11, 12 ],
[ 13, 14, 15, 16 ] ];
rotatematrix(R, C, a);
</script>
|
Output:
5 1 2 3
9 10 6 4
13 11 7 8
14 15 16 12
Time Complexity: O(max(m,n) * max(m,n))
Auxiliary Space: O(m*n)
Please refer complete article on Rotate Matrix Elements for more details!