Skip to content

Commit 0989a2c

Browse files
committed
Add diagonal matrix traversal algorithm
1 parent 40f65e8 commit 0989a2c

File tree

1 file changed

+67
-0
lines changed

1 file changed

+67
-0
lines changed

Diff for: matrix/diagonal_traversal.py

+67
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,67 @@
1+
from typing import List
2+
3+
def find_diagonal_order(mat: List[List[int]]) -> List[int]:
4+
"""
5+
Returns the elements of the matrix in diagonal order.
6+
7+
:param mat: A 2D list representing the matrix.
8+
:return: A list of elements in diagonal order.
9+
:raises ValueError: If the matrix is empty or rows have different lengths.
10+
11+
>>> find_diagonal_order([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
12+
[1, 2, 4, 7, 5, 3, 6, 8, 9]
13+
14+
Example:
15+
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
16+
Algorithm:
17+
Step 1. Initialize variables to track the current row and column.
18+
Step 2. Iterate through the elements of the matrix in a
19+
manner that alternates between moving diagonally up
20+
and down.
21+
"""
22+
if not mat or not mat[0]:
23+
return []
24+
25+
m, n = len(mat), len(mat[0])
26+
27+
# Check for uniformity of row lengths
28+
for row in mat:
29+
if len(row) != n:
30+
raise ValueError("All rows must have the same number of columns.")
31+
32+
result = []
33+
row, col = 0, 0
34+
35+
for _ in range(m * n):
36+
result.append(mat[row][col])
37+
38+
# Determine the direction of traversal
39+
if (row + col) % 2 == 0: # moving up
40+
if col == n - 1: # hit the right boundary
41+
row += 1
42+
elif row == 0: # hit the top boundary
43+
col += 1
44+
else: # move up diagonally
45+
row -= 1
46+
col += 1
47+
else: # moving down
48+
if row == m - 1: # hit the bottom boundary
49+
col += 1
50+
elif col == 0: # hit the left boundary
51+
row += 1
52+
else: # move down diagonally
53+
row += 1
54+
col -= 1
55+
56+
return result
57+
58+
59+
# Driver code
60+
if __name__ == "__main__":
61+
import doctest
62+
63+
doctest.testmod()
64+
65+
# Example usage
66+
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
67+
print(find_diagonal_order(matrix))

0 commit comments

Comments
 (0)