Given a MxN matrix, write a program to replace all elements that do not belong to principal-diagonal & anti-diagonal with Zeros.
Principal-diagonal elements are the set of elements of a matrix that lie on the line joining the top left corner to the bottom right corner.
Anti-diagonal elements are the set of elements of a matrix that lie on the line joining the bottom left corner to the top right corner.Input
The first line of input will contain two space-separated integers, denoting MxN matrix.
The next M lines will contain N space-separated integers.Output
The output should be MxN matrix by replacing elements that do not belong to principal-diagonal and anti-diagonal with Zeros. Print each row as a space separated integers in a single line.
Sample Input 1
5 5
4 3 7 6 4
4 4 7 7 6
9 5 8 5 9
3 6 6 2 4
3 7 4 4 3
Sample Output 1
4 0 0 0 4
0 4 0 7 0
0 0 8 0 0
0 6 0 2 0
3 0 0 0 3
def print_1(mat, n, m):
for i in range(n):
for j in range(m):
print(mat[i][j], end=" ")
print()
def makediagonalnotzero(mat, n, m):
for i in range(n):
for j in range(m):
# right and left diagonal condition
if (i == j or (i + j + 1) == n):
(mat[i][j])
else:
mat[i][j] = 0
# print resultant matrix
print_1(mat, n, m)
# Driver code
if __name__ == "__main__":
n = 3
m = 3
mat = [[2, 1, 7],
[3, 7, 2],
[5, 4, 9]]
makediagonalnotzero(mat, n, m)
Comments
Leave a comment