# Python program to find Diagonal Traversal of a Matrix
# Function that returns elements of given mat in diagonal order
def diagonalOrder(mat):
res = []
n = len(mat)
m = len(mat[0])
# There will be n+m-1 diagonals in total
for line in range(1, n + m):
# Get column index of the first element in
# this diagonal. The index is 0 for first 'n'
# lines and (line - n) for remaining lines
startCol = max(0, line - n)
# Get count of elements in this diagonal
# Count equals minimum of line number, (m-startCol) and n
count = min(line, m - startCol, n)
# Process elements of this diagonal
for j in range(count):
# Calculate row and column indices
# for each element in the diagonal
row = min(n, line) - j - 1
col = startCol + j
res.append(mat[row][col])
return res
if __name__ == "__main__":
mat = [
[ 1, 2, 3, 4 ],
[ 5, 6, 7, 8 ],
[ 9, 10, 11, 12 ],
[ 13, 14, 15, 16 ],
[ 17, 18, 19, 20 ]
]
res = diagonalOrder(mat)
print(" ".join(map(str, res)))