Question #240532

given an MxN integer matrix write a program to

Find all zeros and replace them with the sum of their neighboring elements.

After replacing the zeros set all other elements the corresponding row and column with zeros (excluding the elements which where previously zeros)

Note: consider the upper ,lower,right and left elements as neighboring elements

INPUT

The first line of input is two space seperated integeres M and N

The next M lines of input contain N space seperated integers

OUTPUT

the output should be an MxN matrix

sample input 1

3 3

1 2 3

4 0 2

1 1 8

sample output 1

1 0 3

0 9 0

1 0 8

sample input 2

4 5

4 8 0 0 0

4 7 0 9 7

5 5 6 9 8

7 4 3 6 7

sample output 2

0 0 8 9 7

0 0 22 0 0

5 5 0 0 0

7 4 0 0 0




Expert's answer

m, n = map(int, input().split())
matrix = [[int(x) for x in input().split()] for _ in range(m)]
new_matrix = [matrix[i][:] for i in range(m)]
for i in range(m):
    for j in range(n):
        if not matrix[i][j]:
            new_matrix[i] = [0] * n
            for k in range(m):
                new_matrix[k][j] = 0
for i in range(m):
    for j in range(n):
        if not matrix[i][j]:
            new_matrix[i][j] = matrix[i][max(j - 1, 0)] + matrix[i][min(j + 1, n - 1)] + matrix[max(i - 1, 0)][j] + \
                               matrix[min(i + 1, m - 1)][j]
for i in range(m):
    print(*new_matrix[i])
LATEST TUTORIALS
APPROVED BY CLIENTS