Strange Printer II - Problem

There is a strange printer with the following two special requirements:

  • On each turn, the printer will print a solid rectangular pattern of a single color on the grid. This will cover up the existing colors in the rectangle.
  • Once the printer has used a color for the above operation, the same color cannot be used again.

You are given a m x n matrix targetGrid, where targetGrid[row][col] is the color in the position (row, col) of the grid.

Return true if it is possible to print the matrix targetGrid, otherwise, return false.

Input & Output

Example 1 — Simple Valid Case
$ Input: targetGrid = [[1,1,1],[3,1,3]]
Output: true
💡 Note: First print color 3 in rectangle covering entire grid, then print color 1 in rectangle covering positions (0,0) to (1,1). The overlapping region shows color 1 in final grid, so color 3 must be printed first.
Example 2 — Invalid Case
$ Input: targetGrid = [[1,2],[2,1]]
Output: false
💡 Note: Color 1's bounding rectangle covers entire grid, as does color 2's. But both colors appear in each other's regions, creating a circular dependency that makes printing impossible.
Example 3 — Non-overlapping Colors
$ Input: targetGrid = [[1,1],[2,2]]
Output: true
💡 Note: Colors 1 and 2 have non-overlapping bounding rectangles, so they can be printed in any order without conflicts.

Constraints

  • m == targetGrid.length
  • n == targetGrid[i].length
  • 1 ≤ m, n ≤ 60
  • 1 ≤ targetGrid[row][col] ≤ 60

Visualization

Tap to expand
Strange Printer II - Topological Sort INPUT targetGrid (2x3 matrix) 1 1 1 3 1 3 Color Legend: Color 1 Color 3 Input Array: [[1,1,1], [3,1,3]] m=2, n=3 Colors: {1, 3} ALGORITHM STEPS 1 Find Bounding Box For each color, find min/max row and column positions 2 Build Dependencies If color B inside box of A, then A depends on B Dependency Graph: 1 3 depends 3 Topological Sort Process colors with no incoming edges first 4 Check for Cycles If all colors processed, return true (no cycle) Order: 3 --> 1 (valid) FINAL RESULT Print Sequence: Step A: Print Color 3 Step B: Print Color 1 Output: true Printing is possible! Key Insight: A color A must be printed AFTER color B if B appears inside A's bounding rectangle but A doesn't cover B. This creates dependencies. If the dependency graph has a cycle, printing is impossible. Topological sort detects cycles - if we can process all colors, the answer is TRUE. Time: O(m*n*C), Space: O(C^2). TutorialsPoint - Strange Printer II | Topological Sort Approach
Asked in
Google 25 Amazon 18 Microsoft 12
15.4K Views
Medium Frequency
~35 min Avg. Time
680 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen