Tuesday, December 5, 2017

Reverse & Shift Matrix Edge

Given an R*C matrix containing positive integers, reverse the values along the edges and shift the edge elements by 1 position in clock wise direction.

Input Format:
The first line contains R and C separated by space. Next R lines contain C values separated by space.

Output Format:
R lines containing C values with the values along the edges reversed.

Boundary Conditions: 2 <= R, C <= 100

Example Input/Output 1:
Input:
4 4
85 84 12 26
33 43 91 95
98 17 45 66
57 17 73 10
Output:
33 58 48 21
89 43 91 62
75 17 45 59
71 37 1 66

Solution:
#include <iostream>
using namespace std;
int rev(int f)
{
    int u,r=0;
    while(f!=0)
    {
    u=f%10;
    r=(r*10)+u;
    f=f/10;
    }
    return r;
}
int main(int argc, char** argv)
{
int i,j,r,c;
cin>>r>>c;
int a[r][c],b[r][c]={0};
for(i=0;i<r;i++)
for(j=0;j<c;j++)
cin>>a[i][j];
for(i=0;i<r;i++)
{
if(i==r-1)
 b[i][0]=rev(a[i][1]);
 else
 b[i][0]=rev(a[i+1][0]);
}
for(j=1;j<c;j++)
{
b[0][j]=rev(a[0][j-1]);
}
for(i=1;i<r;i++)
{
b[i][c-1]=rev(a[i-1][c-1]);
}
for(j=1;j<c-1;j++)
{
 b[r-1][j]=rev(a[r-1][j+1]);
}
for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
{
if(b[i][j]==0)
cout<<a[i][j]<<" ";
else
cout<<b[i][j]<<" ";
}
cout<<endl;
}

}
Share: