Matrix rotation

Jyothi
2 min readJan 6, 2022

Below is matrix rotation problem:

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.

Its like flipping the box by 90 degrees right side.

If we consider each element of 4x4 matrix, following steps are involved:

temp = a[0][0],
a[0][0] = a[3][0]
a[3][0] = a[3][3]
a[3][3] = a[0][3]
a[0][3] = temp
temp = a[0][1]
a[0][1] = a[2][0]
a[2][0] = a[3][2]
a[3][2] = a[1][3]
a[1][3] = temp
temp = a[0][2]
a[0][2] =a[1][0]
a[1][0] = a[3][1]
a[3][1] = a[1][3]
a[1][3] = temp

inner matrix:
temp = a[1][1]
a[1][1] = a[2][1]
a[2][1] = a[2][2]
a[2][2] = a[1][2]
a[1][2] = temp

So with the above pattern , we can come up the below logic:

for (ii=0; ii<maxind; ii++)
{
for (jj=ii; jj<maxind-ii; jj++)
{
temp = matrix[ii][jj];
matrix[ii][jj]= matrix[maxind-jj][ii];
matrix[maxind-jj][ii] = matrix[maxind-ii][maxind-jj];
matrix[maxind-ii][maxind-jj] = matrix[jj][maxind-ii];
matrix[jj][maxind-ii] = temp;
/* printf(“\npart1 mat: ii %d, jj %d \n”, ii, jj);
for (kk=0; kk<matrixSize; kk++)
{
for (ll=0; ll<matrixSize; ll++)
printf(“ %d “, matrix[kk][ll]);
printf(“\n”);
}
*/
}
}

Its simple once we understand, but to think and to get the idea, it takes time I feel.

Another solution (change in iterations):

int ii, jj, maxind = matrixSize -1,temp;
int internal_mat_loops,outside_mat_loops;//kk,ll;
outside_mat_loops = (matrixSize+1)/2;
internal_mat_loops = matrixSize/2;
for (ii=0; ii<outside_mat_loops; ii++)
{
for (jj=0; jj<internal_mat_loops; jj++)
{
temp = matrix[ii][jj];
matrix[ii][jj]= matrix[maxind-jj][ii];
matrix[maxind-jj][ii] = matrix[maxind-ii][maxind-jj];
matrix[maxind-ii][maxind-jj] = matrix[jj][maxind-ii];
matrix[jj][maxind-ii] = temp;
}
}

/* printf(“\npart2 mat: ii %d, jj %d \n”, ii, jj);
for (ii=0; ii<matrixSize; ii++)
{
for (jj=0; jj<matrixSize; jj++)
printf(“ %d “, matrix[ii][jj]);
printf(“\n”);
} */
return;

Did nt check the difference of iterations for 1st and 2nd solutions.

Your comments are welcome.

--

--