Tuesday, July 25, 2017

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

Solution:

n,m=int(input()),int(input())
a = [[int(x) for x in input().split()]for _ in range(n)]
for x in a:
    for i in range(len(x)):
        if i == 0:
            print(x[i+1],'',end='')
        elif i == len(x)-1:
            print(x[i-1],'',end='')
        else:
            print(x[i+1]+x[i-1],'',end='')
    print()
Share: