Zig-Zag Order in Matrix
you are given a matrix of dimensions M * N . print the numbers of the matrix in the zig-zag order.
Zig-Zag order of the matrix.
start from the first element in the first row of the matrix and print all the numbers in the first row.
after reaching the end of the first row , move to the last element in the next row and start printing the numbers from the right side of the second line until you reach the first element in the second line .
Now jump to the first element in the third row and repeat the above process.
Sample input:
4 4
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16
SAMPLE OUTPUT :
1 2 3 4 8 7 6 5 9 10 11 12 16 15 14 13
SAMPLE INPUT:
3 4
1 2 3 4
10 11 12 5
9 8 7 6
SAMPLE OUTPUT :
1 2 3 4 5 12 11 10 9 8 7 6
M,N = [int(i) for i in input().split()]
A = []
for i in range(M):
row = [int(j) for j in input().split()]
if len(row) != N:
raise ValueError('Length of row is not N')
A.append(row)
for i in range(M):
if i % 2 == 0:
[print(i, end=' ') for i in A[i]]
else:
[print(i, end=' ') for i in reversed(A[i])]
print()
Comments
Leave a comment