Skip to content

Commit 70d82ab

Browse files
authored
Update strange-printer-ii.py
1 parent f3747fd commit 70d82ab

File tree

1 file changed

+38
-8
lines changed

1 file changed

+38
-8
lines changed

Python/strange-printer-ii.py

Lines changed: 38 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,43 @@ def has_cycle(adj, color, lookup):
2828
elif step == 2:
2929
lookup[color] = VISITED
3030
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
3268

3369
MAX_COLOR = 60
3470
adj = collections.defaultdict(set)
@@ -50,10 +86,4 @@ def has_cycle(adj, color, lookup):
5086
adj[color].add(targetGrid[r][c])
5187

5288
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

Comments
 (0)