1
+
2
+ # MINIMUM PASSES OF MATRIX
3
+
4
+ # O(W * H) time and space
5
+ def minimumPassesOfMatrix (matrix ):
6
+ # Write your code here.
7
+ passes = convertNegatives (matrix )
8
+ return passes - 1 if not containsNegative (matrix ) else - 1
9
+
10
+ def convertNegatives (matrix ):
11
+ nextPassQueue = getAllPositivePositions (matrix )
12
+
13
+ passes = 0
14
+ while len (nextPassQueue ) > 0 :
15
+ currentPassQueue = nextPassQueue
16
+ nextPassQueue = []
17
+
18
+ while len (currentPassQueue ) > 0 :
19
+ row , column = currentPassQueue .pop (0 )
20
+ adjacentPositions = getAdjacentPositions (row , column , matrix )
21
+ for position in adjacentPositions :
22
+ r , c = position
23
+ value = matrix [r ][c ]
24
+ if value < 0 :
25
+ matrix [r ][c ] *= - 1
26
+ nextPassQueue .append ([r , c ])
27
+
28
+ passes += 1
29
+ return passes
30
+
31
+ def getAllPositivePositions (matrix ):
32
+ positives = []
33
+
34
+ for row in range (len (matrix )):
35
+ for col in range (len (matrix [row ])):
36
+ value = matrix [row ][col ]
37
+ if value > 0 :
38
+ positives .append ([row , col ])
39
+
40
+ return positives
41
+
42
+ def getAdjacentPositions (row , col , matrix ):
43
+ adjacents = []
44
+
45
+ if row > 0 :
46
+ adjacents .append ([row - 1 , col ])
47
+ if row < len (matrix ) - 1 :
48
+ adjacents .append ([row + 1 , col ])
49
+ if col > 0 :
50
+ adjacents .append ([row , col - 1 ])
51
+ if col < len (matrix [0 ]) - 1 :
52
+ adjacents .append ([row , col + 1 ])
53
+
54
+ return adjacents
55
+
56
+ def containsNegative (matrix ):
57
+ for row in matrix :
58
+ for value in row :
59
+ if value < 0 :
60
+ return True
61
+ return False
0 commit comments