# Matrix Layer Rotation HackerRank Solution in C, C++, Java, Python

You are given a 2D matrix of dimension m*n 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 4×5 matrix is represented by the following figure. Note that in one rotation, you have to shift elements by one step only.

matrix-rotation

It is guaranteed that the minimum of m and n will be even.

As an example rotate the Start matrix by 2:

Start         First           Second
1 2 3 4        2  3  4  5      3  4  5  6
12 1 2 5  ->   1  2  3  6 ->   2  3  4  7
11 4 3 6      12  1  4  7       1  2  1  8
10 9 8 7      11 10  9  8     12 11 10  9

Function Description

Complete the matrixRotation function in the editor below. It should print the resultant 2D integer array and return nothing.

matrixRotation has the following parameter(s):

matrix: a 2D array of integers
r: an integer that represents the rotation factor

Input Format

The first line contains three space separated integers, m, n, and r, the number of rows and columns in matrix, and the required rotation.
The next lines contain space-separated integers representing the elements of a row of .

Output Format

Print each row of the rotated matrix as space-separated integers on separate lines.

Sample Input

Sample Input #01

4 4 2
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16

Sample Output #01

3 4 8 12
2 11 10 16
1 7 6 15
5 9 13 14

Explanation #01

The matrix is rotated through two rotations.

1  2  3  4      2  3  4  8      3  4  8 12
5  6  7  8      1  7 11 12      2 11 10 16
9 10 11 12  ->  5  6 10 16  ->  1  7  6 15
13 14 15 16      9 13 14 15      5  9 13 14

Sample Input #02

5 4 7
1 2 3 4
7 8 9 10
13 14 15 16
19 20 21 22
25 26 27 28

Sample Output #02

28 27 26 25
22 9 15 19
16 8 21 13
10 14 20 7
4 3 2 1

Explanation 02

The various states through 7 rotations:

1  2  3  4      2  3  4 10    3  4 10 16    4 10 16 22
7  8  9 10      1  9 15 16    2 15 21 22    3 21 20 28
13 14 15 16 ->  7  8 21 22 -> 1  9 20 28 -> 2 15 14 27 ->
19 20 21 22    13 14 20 28    7  8 14 27    1  9  8 26
25 26 27 28    19 25 26 27    13 19 25 26   7 13 19 25

10 16 22 28    16 22 28 27    22 28 27 26    28 27 26 25
4 20 14 27    10 14  8 26    16  8  9 25    22  9 15 19
3 21  8 26 ->  4 20  9 25 -> 10 14 15 19 -> 16  8 21 13
2 15  9 25     3 21 15 19     4 20 21 13    10 14 20  7
1  7 13 19     2  1  7 13     3  2  1  7     4  3  2  1

Sample Input #03

2 2 3
1 1
1 1

Sample Output #03

1 1
1 1

Explanation #03

All of the elements are the same, so any rotation will repeat the same matrix.

TABLE OF CONTENTS

## Matrix Layer Rotation HackerRank Solution in C

#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>

int main() {

int m, n, i, j, x, rings;
long long int r, arr[300][300], p ,q, temp_r;;
char str[10000];
char* _p;
scanf("%d%d%lld", &m, &n, &r);
fgetc(stdin);

for(i=0; i<m; i++)
{
fgets(str, 10000, stdin);
for(_p=strtok(str, " "), j=0; _p!=NULL; _p=strtok(NULL, " "), j++)
{
arr[i][j] = atoll(_p);
}
}

rings = (m<n)?m:n;
int ring_m, ring_n;
ring_m = m;
ring_n = n;
//temp_r=r;

for(x=0; x<(rings/2); x++)
{
temp_r = r % ( ( (m-(x*2)) + (n-(x*2)) - 2 )*2 );

while(temp_r>0)
{
i=j=x;
p = arr[i][j];
while(i<ring_m)
{
q = arr[i][j];
arr[i][j] = p;
p = q;
i++;
}
i--;
j++;
while(j<ring_n)
{
q = arr[i][j];
arr[i][j] = p;
p = q;
j++;
}
j--;
i--;
while(i>=x)
{
q = arr[i][j];
arr[i][j] = p;
p = q;
i--;
}
i++;
j--;
while(j>=x)
{
q = arr[i][j];
arr[i][j] = p;
p = q;
j--;
}
temp_r--;
}
ring_m--;
ring_n--;
}
for(i=0; i<m; i++)
{
for(j=0; j<n; j++)
{
printf("%lld ",arr[i][j]);
}
printf("\n");
}
return 0;
}

## Matrix Layer Rotation HackerRank Solution in C++

//
//  main.cpp
//  MatrixRotation
//
//  Created by Satya Vivek on 6/29/15.
//  Copyright (c) 2015 Satya Vivek. All rights reserved.
//

#include <iostream>
#include <vector>

using namespace::std;

struct element{
int row,col,value;
};

int countLength(int highC,int highR,int lowC,int lowR,vector <element> &v){

int a = lowC,b = lowR,count=0;
struct element e;
e.row = a;
e.col = b;
v.push_back(e);
do{
count++;
a++;
e.row = a;
e.col = b;
v.push_back(e);
}while (a<highR);
do{
count++;
b++;
e.row = a;
e.col = b;
v.push_back(e);
}while (b<highC);
do{
count++;
a--;
e.row = a;
e.col = b;
v.push_back(e);
}while (a>lowR);
do{
count++;
b--;
e.row = a;
e.col = b;
v.push_back(e);
}while (b>lowC);
return count;
}

void changeMatrix(int arr[][300],int highC,int lowC,int highR,int lowR,int r,int c,int k){

vector<element> v;
int len = countLength(highC,highR,lowC,lowR,v);
k = k%len;
v.pop_back();

for (int i=0; i<v.size();i++) {
int n = (i+k)%len;
v[n].value = arr[v[i].row][v[i].col];
}

for (int i=0; i<v.size(); i++) {
int r = v[i].row;
int c = v[i].col;
arr[r][c] = v[i].value;
}

}

int main(int argc, const char * argv[]) {

int r,c,k,arr[300][300];
cin>>r>>c>>k;
for (int i=0; i<r; i++) {
for (int j=0; j<c; j++) {
cin>>arr[i][j];
}
}
int highC=c-1,highR=r-1,lowC=0,lowR=0;
while (true) {

if (highC-lowC<1||highR-lowR<1) {
break;
}
else{
changeMatrix(arr,highC,lowC,highR,lowR,r,c,k);
}
highC--;
highR--;
lowC++;
lowR++;
}
for (int i=0; i<r; i++) {
for (int j=0; j<c; j++) {
cout<<arr[i][j]<<" ";
}
cout<<endl;
}
}

## Matrix Layer Rotation HackerRank Solution in Java

# Enter your code here. Read input from STDIN. Print output to STDOUT

def iterate_circle(mat, m, n, i):
for j in xrange(i, m - i - 1):
yield (j, i)
for j in xrange(i, n - i - 1):
yield (m - i - 1, j)
for j in xrange(m - i - 1, i, -1):
yield (j, n - i - 1)
for j in xrange(n - i - 1, i, -1):
yield (i, j)

def rotate(mat, m, n, r):
for i in xrange(min(m, n) / 2):
circle_length = 2 * (m + n - 4 * i) - 4
offset = circle_length - (r % circle_length)
if offset == circle_length:
continue
line = [mat[x][y] for (x, y) in iterate_circle(mat, m, n, i)]
for (x, y) in iterate_circle(mat, m, n, i):
mat[x][y] = line[offset]
offset = (offset + 1) % circle_length

[m, n, r] = [int(s) for s in raw_input().split(' ')]
mat = [[0 for j in xrange(n)] for i in xrange(m)]
for i in xrange(m):
for (j, s) in enumerate(raw_input().split(' ')):
mat[i][j] = int(s)
rotate(mat, m, n, r)
for i in xrange(m):
for j in xrange(n):
print mat[i][j],
print ''

## Matrix Layer Rotation HackerRank Solution in Python

import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;

public class Solution {

public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int m = scanner.nextInt(), n = scanner.nextInt(), r = scanner.nextInt();
int[][] a = new int[m][n];
//r %= 2 * ( m + n - 2);
//System.out.println("r: " + r);
for(int i = 0; i < m; ++ i)
for(int j = 0; j < n; ++ j)
a[i][j] = scanner.nextInt();

scanner.close();

int layers = Math.min(m, n) / 2;

//each layer contains 2 * (m + n - 2 - 4 * layer) number of items.
//the variable layer begins from 0 from outside, and increments by 1.
for(int layer = 0; layer < layers; ++ layer)
{
for(int x = 0; x < r % (2 * (m + n - 2 - 4 * layer)); ++ x)
{
int i = layer, j = layer;
int temp = a[layer][layer];

while(i < m - 1 - layer)
{
int temp2 = a[i + 1][j];
a[i + 1][j] = temp;
temp = temp2;
i += 1;
}

while(j < n - 1 - layer)
{
int temp2 = a[i][j + 1];
a[i][j + 1] = temp;
temp = temp2;
j += 1;
}

while(i > layer)
{
int temp2 = a[i - 1][j];
a[i - 1][j] = temp;
temp = temp2;
i -= 1;
}

while(j > layer)
{
int temp2 = a[i][j - 1];
a[i][j - 1] = temp;
temp = temp2;
j -= 1;
}
}
}

display(a);
}

private static void display(int[][] a)
{
for(int x = 0; x < a.length; ++ x)
{
for(int y = 0; y < a[x].length; ++ y)
System.out.print(a[x][y] + " ");

System.out.println();
}
}
}

## Matrix Layer Rotation HackerRank Solution in C#

using System;
using System.Collections.Generic;
using System.IO;
class Solution {
static void Main(String[] args) {
int[] ia = GetInts(Console.ReadLine(), 3);
int rows = ia[0];
int cols = ia[1];
int cnt = ia[2];
int[][] mx = new int[rows][];
for(int i = 0; i < rows; i++)
{
mx[i] = GetInts(Console.ReadLine(), cols);
}

Rotate(mx, rows, cols, cnt);

for (int i = 0; i < rows; i++)
{
Console.WriteLine(GetRow(mx[i]));
}

}

private static void Rotate(int[][] mx, int rows, int cols, int cnt)
{
int startR = 0, startCol = 0;
while(rows > 1 && cols > 1)
{
RotateOut(mx, rows, cols, startR, startCol, cnt);
rows -= 2;
cols -= 2;
startR++;
startCol++;

}

}

private static string GetRow(int[] xx)
{
string res = "";
foreach(int i in xx)
{
res += i + " ";
}
return res.Trim();
}

private static void RotateOut(int[][] mx, int rows, int cols, int startR, int startCol, int cnt)
{
cnt = cnt % (2 *(cols  +  rows - 2));
for (int x = 0; x < cnt; x++)
{
int t = mx[startR][startCol];

for (int i = startCol; i < startCol + cols - 1; i++)
mx[startR][i] = mx[startR][i + 1];

int c = startCol + cols - 1;
for (int i = startR; i < startR + rows - 1; i++)
mx[i][c] = mx[i + 1][c];

int r = startR + rows - 1;
for (int i = startCol + cols - 1; i >= startCol + 1; i--)
mx[r][i] = mx[r][i -1];

for (int i = startR + rows - 1; i >= 1 + startR; i--)
mx[i][startCol] = mx[i-1][startCol];

mx[startR + 1][startCol] = t;
}
}

static int[] GetInts(string inp, int cnt)
{
string[] vals = inp.Split(new char[] { ' ' });
int[] res = new int[cnt];
for (int i = 0; i < cnt; i++)
{
res[i] = Convert.ToInt32(vals[i]);
}
return res;
}
}

Attempt Matrix Layer Rotation HackerRank Challenge

Next HackerRank Challenge Solution