Skip to content

Instantly share code, notes, and snippets.

@rvndbalaji
Last active July 22, 2017 03:54
Show Gist options
  • Save rvndbalaji/89d3af4cce655709b93c0c3868314547 to your computer and use it in GitHub Desktop.
Save rvndbalaji/89d3af4cce655709b93c0c3868314547 to your computer and use it in GitHub Desktop.
Matrix Layer Rotation - HackerRank Coding Challenge | https://www.hackerrank.com/challenges/matrix-rotation
/*
You are given a 2D matrix, a, of dimension MxN and a positive integer R. You have to rotate the matrix R times and print the resultant matrix. Rotation should be in anti-clockwise direction.
Rotation of a 4x5 matrix is represented by the following figure. Note that in one rotation, you have to shift elements by one step only (refer sample tests for more clarity).
Matrix-rotation
It is guaranteed that the minimum of M and N will be even.
Input
First line contains three space separated integers, M, N and R, where M is the number of rows, N is number of columns in matrix, and R is the number of times the matrix has to be rotated.
Then M lines follow, where each line contains N space separated positive integers. These M lines represent the matrix.
Output
Print the rotated matrix.
Constraints
2 <= M, N <= 300
1 <= R <= 109
min(M, N) % 2 == 0
1 <= aij <= 108, where i ∈ [1..M] & j ∈ [1..N]
Sample Input #00
4 4 1
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16
Sample Output #00
2 3 4 8
1 7 11 12
5 6 10 16
9 13 14 15
*/
//Code
#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
int min(int a,int b)
{
return (a<b)?a:b;
}
int main()
{
int m,n,r,i,j,a[50][50],initial,num_rect=0,count=0,x,y,k,row,col;
printf("Enter the number of rows and coloumns : ");
scanf("%d%d",&m,&n);
num_rect = (min(m,n))/2;
printf("Enter the number of rotations\n");
scanf("%d",&r);
printf("Enter the matrix \n");
for(i=1;i<=m;i++)
for(j=1;j<=n;j++)
scanf("%d",&a[i][j]);
for(k=1;k<=r;k++)
{
x=m;
y=n;
for(count=1;count<=num_rect;count++)
{
row=count;
col=count;
initial = a[count][count];
do
{
if( (col+1) <= y )
{
a[row][col] = a[row][col+1];
col++;
}
else if( (row+1) <= x )
{
a[row][col] = a[row+1][col];
row++;
}
}while(!(row==x && col==y));
do
{
if( (col-1) >= count )
{
a[row][col] = a[row][col-1];
col--;
}
else if( (row-1) >= count )
{
a[row][col] = a[row-1][col];
row--;
}
}while(!( (row-1)==count && col==count) );
a[row][col] = initial;
x--;
y--;
}
}
printf("\nMatrix rotated %d times is : \n",r);
for(i=1;i<=m;i++)
{
for(j=1;j<=n;j++)
{
printf(" %d ",a[i][j]);
}
printf("\n");
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment