Given an M X N 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 in the corresponding row and column with zeros
(excluding the elements which we previously zeros)
Note: consider the upper, lower, right and left elements as neighboring elements
Input
The first line of input is two space-separated M and N
The next M lines of input contain N space-separated integers
Output
The output should be an M X N matrix
SampleInput1:
3 3
1 2 3
4 0 2
1 1 8
Sample Output1:
1 0 3
0 9 0
1 0 8
SampleInput2:
4 5
4 8 0 0 0
4 7 0 9 7
5 5 6 9 8
7 4 3 6 7
SampleOutput2:
0 0 8 9 7
0 0 22 0 0
5 5 0 0 0
7 4 0 0 0
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])
Comments
Leave a comment