Answer the question
In order to leave comments, you need to log in
How to do a zigzag traversal of a square matrix in python?
There is an NxN matrix, you need to make a traversal in this way and add elements to the list.
Answer the question
In order to leave comments, you need to log in
I sketched it on a tablet without recursions, errors are possible, but the algorithm is simple - we take square blocks of the matrix in turn and select their diagonal
matrix = [
[11, 12, 13, 14],
[21, 22, 23, 24],
[31, 32, 33, 34],
[41, 42, 43, 44],
]
def walk(matrix):
zigzag = []
for index in range(1, len(matrix)):
slice = [i[:index] for i in matrix[:index]]
diag = [slice[i][len(slice)-i-1] for i in range(len(slice))]
if len(diag) % 2:
diag.reverse()
zigzag += diag
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question