Z
Z
Zakhar Orlov2014-10-29 20:21:22
Python
Zakhar Orlov, 2014-10-29 20:21:22

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.
40de05050e6c443b8203614c2654c88f.png

Answer the question

In order to leave comments, you need to log in

2 answer(s)
V
Valentine, 2014-10-29
@divalign

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

S
Sergey Lerg, 2014-10-29
@Lerg

rosettacode.org/wiki/Zig-zag_matrix#Python

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question