@@ -28,7 +28,43 @@ def has_cycle(adj, color, lookup):
28
28
elif step == 2 :
29
29
lookup [color ] = VISITED
30
30
return False
31
-
31
+
32
+ boxes = collections .defaultdict (lambda :[len (targetGrid ), len (targetGrid [0 ]), - 1 , - 1 ])
33
+ adj = collections .defaultdict (set )
34
+ for r , row in enumerate (targetGrid ):
35
+ for c , v in enumerate (row ):
36
+ boxes [v ][0 ] = min (boxes [v ][0 ], r )
37
+ boxes [v ][1 ] = min (boxes [v ][1 ], c )
38
+ boxes [v ][2 ] = max (boxes [v ][2 ], r )
39
+ boxes [v ][3 ] = max (boxes [v ][3 ], c )
40
+ for color , (min_r , min_c , max_r , max_c ) in boxes .iteritems ():
41
+ for r in xrange (min_r , max_r + 1 ):
42
+ for c in xrange (min_c , max_c + 1 ):
43
+ if targetGrid [r ][c ] != color :
44
+ adj [color ].add (targetGrid [r ][c ])
45
+
46
+ lookup = {}
47
+ return all (color in lookup or not has_cycle (adj , color , lookup ) for color in boxes .iterkeys ())
48
+
49
+
50
+ # Time: O(c * m * n + e), c is the number of colors
51
+ # , e is the number of edges in adj, at most O(c^2)
52
+ # Space: O(e)
53
+ class Solution2 (object ):
54
+ def isPrintable (self , targetGrid ):
55
+ """
56
+ :type targetGrid: List[List[int]]
57
+ :rtype: bool
58
+ """
59
+ VISITING , VISITED = range (2 )
60
+ def has_cycle (adj , color , lookup ):
61
+ lookup [color ] = VISITING
62
+ for new_color in adj [color ]:
63
+ if (new_color not in lookup and has_cycle (adj , new_color , lookup )) or \
64
+ lookup [new_color ] == VISITING :
65
+ return True
66
+ lookup [color ] = VISITED
67
+ return False
32
68
33
69
MAX_COLOR = 60
34
70
adj = collections .defaultdict (set )
@@ -50,10 +86,4 @@ def has_cycle(adj, color, lookup):
50
86
adj [color ].add (targetGrid [r ][c ])
51
87
52
88
lookup = {}
53
- for color in xrange (1 , MAX_COLOR + 1 ):
54
- if color in lookup :
55
- continue
56
- if has_cycle (adj , color , lookup ):
57
- return False
58
- return True
59
-
89
+ return all (color in lookup or not has_cycle (adj , color , lookup ) for color in xrange (1 , MAX_COLOR + 1 ))
0 commit comments