Given an N X M integer matrix, rotate it bye 90 in c clock wise. for example if input matrix is

1 2 3 8
4 5 6 7
7 8 9 7

Then the 90 degree clock wise rotation of above matrix would be

7 4 1
8 5 2
9 6 3
7 7 8

Solution:
(1)The input matrix
1 2 3 8
4 5 6 7
7 8 9 7

is having row=3 and column=4 , after rotation the output matrix

7 4 1
8 5 2
9 6 3
7 7 8

is having row=4 and column=3.
(2) Look at

1 2 3 8             7 4 1
4 5 6 7 ====> 8 5 2
7 8 9 7             9 6 3
7 7 8

We can see that first row of input matrix [1 2 3 8] is last column of output matrix

[1]
[2]
[3]
[8]
Now implement it in c:

 

#include<stdio.h>

#define row 3
#define col 4

int mat[][col]={{1,2,3,8},
	        {4,5,6,7},
                {7,8,9,7}};

void rotate90_d(int m[row][col], int o[col][row]);

int main()
{
	int i=0;
        int j=0;
	for(i=0;i<row;i++)
	{
		for(j=0;j<col;j++)
		{
			printf("%d ",mat[i][j]);
		}
        printf("\n");
	}
        /* createa temp matrix colxrow size */
        int o[col][row];
       /* call rotation*/
	rotate90_d(mat,o);

     /* print out put */
        printf("the output after 90 degree rotation:\n");
	for(i=0;i<col;i++)
	{
		for(j=0;j<row;j++)
		{
			printf("%d ",o[i][j]);
		}
        printf("\n");
	}

return 0;
}

void rotate90_d(int m[row][col],int o[col][row])
{

	int i=0;
        int j=0;
	for(i=0;i<row;i++)
	{
		for(j=0;j<col;j++)
		{
			o[j][row-1-i] = mat[i][j];
		}
	}
}

output:

1 2 3 8
4 5 6 7
7 8 9 7
the output after 90 degree rotation:
7 4 1
8 5 2
9 6 3
7 7 8



Related Contents to follow