1+ Given a matrix of M x N elements (M rows , N columns ),
2+ return all elements of the matrix in diagonal order as shown in the below image .
3+
4+ Example :
5+ Input :
6+ [
7+ [ 1 , 2 , 3 ],
8+ [ 4 , 5 , 6 ],
9+ [ 7 , 8 , 9 ]
10+ ]
11+
12+ Output : [1 ,2 ,4 ,7 ,5 ,3 ,6 ,8 ,9 ]
13+
14+ Explanation :
15+
16+ Note :
17+
18+ The total number of elements of the given matrix will not exceed 10 ,000.
19+
20+ # O(m*n) Time and O(1) Space
21+ class Solution :
22+ def findDiagonalOrder (self , matrix : List [List [int ]]) -> List [int ]:
23+
24+ if not matrix :
25+ return []
26+
27+ row = 0
28+ col = 0
29+ m , n = len (matrix ), len (matrix [0 ])
30+
31+ isUp = True
32+ result = []
33+
34+ while row < m and col < n :
35+
36+ if isUp :
37+
38+ while row > 0 and col < n - 1 :
39+ result .append (matrix [row ][col ])
40+ row -= 1
41+ col += 1
42+
43+ result .append (matrix [row ][col ])
44+
45+ if col == n - 1 :
46+ row += 1
47+ else :
48+ col += 1
49+
50+ else :
51+
52+ while col > 0 and row < m - 1 :
53+ result .append (matrix [row ][col ])
54+ row += 1
55+ col -= 1
56+
57+ result .append (matrix [row ][col ])
58+
59+ if row == m - 1 :
60+ col += 1
61+ else :
62+ row += 1
63+
64+ isUp = not isUp
65+
66+
67+ return result
68+
69+ # An easy to understand solution
70+ class Solution (object ):
71+ def findDiagonalOrder (self , matrix ):
72+ """
73+ :type matrix: List[List[int]]
74+ :rtype: List[int]
75+ """
76+ d = {}
77+ #loop through matrix
78+ for i in range (len (matrix )):
79+ for j in range (len (matrix [i ])):
80+ #if no entry in dictionary for sum of indices aka the diagonal, create one
81+ if i + j not in d :
82+ d [i + j ] = [matrix [i ][j ]]
83+ else :
84+ #If you've already passed over this diagonal, keep adding elements to it!
85+ d [i + j ].append (matrix [i ][j ])
86+ # we're done with the pass, let's build our answer array
87+ ans = []
88+ #look at the diagonal and each diagonal's elements
89+ for entry in d .items ():
90+ #each entry looks like (diagonal level (sum of indices), [elem1, elem2, elem3, ...])
91+ #snake time, look at the diagonal level
92+ if entry [0 ] % 2 == 0 :
93+ #Here we append in reverse order because its an even numbered level/diagonal.
94+ [ans .append (x ) for x in entry [1 ][::- 1 ]]
95+ else :
96+ [ans .append (x ) for x in entry [1 ]]
97+ return ans
98+
99+ # Key Concept
100+ 1. Diagonals are defined by the sum of indicies in a 2 dimensional array
101+ 2. The snake phenomena can be achieved by reversing every other diagonal level , therefore check if divisible by 2
0 commit comments