1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43
| def print_matrix_zigzag(matrix): row1 = 0 col1 = 0 row2 = 0 col2 = 0 end_row = len(matrix) - 1 end_col = len(matrix[0]) - 1 from_up = False result = []
while row1 <= end_row: result.extend(get_diagonal(matrix, row1, col1, row2, col2, from_up)) row1 = row1 + 1 if col1 == end_col else row1 col1 = col1 if col1 == end_col else col1 + 1 col2 = col2 + 1 if row2 == end_row else col2 row2 = row2 if row2 == end_row else row2 + 1 from_up = not from_up
print(result)
def get_diagonal(m, row1, col1, row2, col2, from_up): tmp_result = [] if from_up: for i in range(row1, row2 + 1): tmp_result.append(m[i][col1]) col1 -= 1 else: for i in range(row2, row1 - 1, -1): tmp_result.append(m[i][col2]) col2 += 1
return tmp_result
if __name__ == '__main__': input_matrix = [ [1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12] ]
print_matrix_zigzag(input_matrix)
|