Breaking

Monday 24 July 2017

2D Matrix - Elements Adjacent Sum

                 2D Matrix - Elements Adjacent Sum

                                                       

Given a matrix of R rows and C columns, for each element print the sum of the adjacent elements.

Input Format:
The first line contains R
The second line contains C
Next R lines each contains C values separated by a space

Output Format:
R lines each containing C values which represent the sum of the adjacent elements.

Boundary Conditions:
2 <= R,C <= 50
1 <= Matrix Elements <= 100

Example Input/Output 1:
Input:
5 5
11 11 5 6 18
12 4 16 9 19
5 20 7 5 2
20 19 7 2 11
16 18 5 16 17

Output:
11 16 17 23 6
4 28 13 35 9
20 12 25 9 5
19 27 21 18 2
18 21 34 22 16

Code:

#include <iostream>
using namespace std;
int main(int argc, char** argv)
{
int i,j,r,c,sum=0;
cin>>r>>c;
int arr[r][c];
for(i=0;i<r;i++)
        for(j=0;j<c;j++)
            cin>>arr[i][j];
   
for(i=0;i<r;i++)
    {
        for(j=0;j<c;j++)
            {
                if(j==0)
                    sum=arr[i][j+1];
                else if(j==c-1)
                    sum=arr[i][j-1];
                else
                    sum=arr[i][j-1]+arr[i][j+1];
                cout<<sum<<" ";
            }
        cout<<"\n";
    }


}

No comments:

Post a Comment

Like