Last active
November 24, 2022 15:32
-
-
Save ibeauregard/0fa1bbb447cf3f2a89704926009e525e to your computer and use it in GitHub Desktop.
An elegant way to walk a matrix along its minor diagonals. Minor diagonal d is made of all elements mat[i][j] such that i + j = d. Minor diagonal d is walked towards row 0 if d is even; if d is odd it is walked towards column 0.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from collections import deque | |
from itertools import chain | |
def diagonal_walk(mat): | |
m, n = len(mat), len(mat[0]) | |
diagonals = [deque() for _ in range(m + n - 1)] | |
for i in range(m): | |
for j in range(n): | |
if (i + j) % 2 == 0: | |
diagonals[i + j].appendleft(mat[i][j]) | |
else: | |
diagonals[i + j].append(mat[i][j]) | |
return list(chain(*diagonals)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment