Problem Description
Given an m x n matrix targetGrid where targetGrid[row][col] represents a color at position (row, col), determine if it is possible to print the grid using a strange printer. The printer can only print a solid rectangular pattern of a single color in one turn and each color may be used only once. When printing a rectangle, it covers any colors underneath. Return true if you can achieve targetGrid with a sequence of printing operations; otherwise, return false.
Key Insights
- For each color present, determine its bounding rectangle (smallest rectangle that covers all occurrences).
- Within that bounding rectangle, any cell that does not match the current color is evidence that another color was printed after the current one. This sets up a dependency relation.
- Build a dependency graph where an edge from color A to color B indicates that A must be printed before B.
- The problem reduces to checking if the dependency graph has a valid topological ordering (i.e. no cycles).
Space and Time Complexity
Time Complexity: O(m * n + k * m * n) where k is the number of distinct colors (k ≤ 60), so essentially O(m * n) Space Complexity: O(k + m * n) for storing the graph and the bounding boxes.
Solution
We start by scanning the targetGrid to determine, for each color, its minimum and maximum row and column indices (its bounding rectangle). Then, for each color, we examine every cell in its bounding rectangle. If a cell contains a different color D, then that means color D was painted over color C and should appear later. Therefore, we add an edge from C to D in our dependency graph. Once the graph is built, we perform a topological sort. If we can obtain a complete ordering without detecting a cycle, then the sequence of printer operations exists to form the targetGrid; otherwise, it is impossible.