forked from super30admin/Array-1
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathp27_medium_diagonaltraverse.py
More file actions
52 lines (45 loc) · 1.22 KB
/
p27_medium_diagonaltraverse.py
File metadata and controls
52 lines (45 loc) · 1.22 KB
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
44
45
46
47
48
49
50
51
52
"""
Leetcode-
Given an m x n matrix mat, return an array of all the elements of the array in a diagonal order.
:return
Tc:- O(m*n)
SC: O(m*n)
Ran on leetcode- yes
"""
class Solution:
def findDiagonalOrder(self, mat):
if mat==None :
return []
rows=len(mat)
columns=len(mat[0])
i,j=0,0
resultArray=[0]*(rows*columns)
indexResultArray=0
direction=1 ##up
while indexResultArray<rows*columns:
resultArray[indexResultArray]=mat[i][j]
indexResultArray+=1
###now we gotta find next i and j in the matrix
if direction==1:
if j==columns-1:
i+=1
direction=-1
elif i==0:
j+=1
direction=-1
else:
i-=1
j+=1
else:
if i==rows-1:
j+=1
direction = 1
elif j==0:
i+=1
direction=1
else:
j-=1
i+=1
mat = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
solve=Solution()
print(solve.findDiagonalOrder(mat))