- Translate each rule into one explicit state update.
- Maintain the invariant after every processed item.
- Return the accumulated state once all relevant input has been handled.
Code notes
- 53 lines of Python from the credited upstream file 1591.py.
- The implementation visibly relies on sequence storage, ordered lookup.
- No explicit loop blocks detected.
Complexity
Count the number and nesting of passes over the input, then include the maintained containers in the memory estimate.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1from enum import Enum2 3 4class State(Enum):5 INIT = 06 VISITING = 17 VISITED = 28 9 10class Solution:11 def isPrintable(self, targetGrid: list[list[int]]) -> bool:12 MAX_COLOR = 6013 m = len(targetGrid)14 n = len(targetGrid[0])15 16 17 graph = [set() for _ in range(MAX_COLOR + 1)]18 19 for color in range(1, MAX_COLOR + 1):20 21 minI = m22 minJ = n23 maxI = -124 maxJ = -125 for i in range(m):26 for j in range(n):27 if targetGrid[i][j] == color:28 minI = min(minI, i)29 minJ = min(minJ, j)30 maxI = max(maxI, i)31 maxJ = max(maxJ, j)32 33 34 for i in range(minI, maxI + 1):35 for j in range(minJ, maxJ + 1):36 if targetGrid[i][j] != color:37 graph[color].add(targetGrid[i][j])38 39 states = [State.INIT] * (MAX_COLOR + 1)40 41 def hasCycle(u: int) -> bool:42 if states[u] == State.VISITING:43 return True44 if states[u] == State.VISITED:45 return False46 states[u] = State.VISITING47 if any(hasCycle(v) for v in graph[u]):48 return True49 states[u] = State.VISITED50 return False51 52 return not (any(hasCycle(i) for i in range(1, MAX_COLOR + 1)))53