Skip to content

Commit ef873c8

Browse files
Time: 1188 ms (6.20%) | Memory: 19.8 MB (5.52%) - LeetSync
1 parent b706150 commit ef873c8

File tree

1 file changed

+54
-0
lines changed

1 file changed

+54
-0
lines changed
Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
from collections import deque
2+
3+
def isInside(i, j, box):
4+
n, e, s, w = box
5+
return n <= i <= s and w <= j <= e
6+
7+
def cycle(n, graph, v, v_nodes):
8+
if n not in graph:
9+
return False
10+
11+
v.append(n)
12+
v_nodes.add(n)
13+
14+
for nn in graph[n]:
15+
if nn in v or cycle(nn, graph, v, v_nodes):
16+
return True
17+
18+
v.pop()
19+
return False
20+
21+
22+
class Solution:
23+
def isPrintable(self, targetGrid: List[List[int]]) -> bool:
24+
boxes = {}
25+
26+
for i in range(len(targetGrid)):
27+
for j in range(len(targetGrid[i])):
28+
v = targetGrid[i][j]
29+
30+
if v not in boxes:
31+
boxes[v] = (i, j, i, j) # N E S W
32+
else:
33+
n, e, s, w = boxes[v]
34+
boxes[v] = (min(n, i), max(e, j), max(s, i), min(w, j))
35+
36+
graph = {}
37+
38+
for i in range(len(targetGrid)):
39+
for j in range(len(targetGrid[i])):
40+
v = targetGrid[i][j]
41+
42+
for k, box in boxes.items():
43+
if k == v:
44+
continue
45+
if isInside(i, j, box):
46+
graph[v] = graph.get(v, set()) | {k}
47+
48+
v_nodes = set()
49+
50+
51+
for start in boxes:
52+
if cycle(start, graph, [], v_nodes):
53+
return False
54+
return True

0 commit comments

Comments
 (0)