[LeetCode] Strange Printer II

1591. Strange Printer II

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
class Solution {
bool isOnTop(vector<vector<int>>& grid, array<int,4>& range, int color) {
int fr = range[0], fc = range[1], tr = range[2], tc = range[3];
for(int i = fr; i <= tr; i++) {
for(int j = fc; j <= tc; j++) {
if(grid[i][j] == color or grid[i][j] == 0) continue;
return false;
}
}

for(int i = fr; i <= tr; i++) {
for(int j = fc; j <= tc; j++) {
grid[i][j] = 0;
}
}

return true;
}
public:
bool isPrintable(vector<vector<int>>& targetGrid) {
unordered_map<int, array<int,4>> colorRange;
int n = targetGrid.size(), m = targetGrid[0].size();
for(int i = 0; i < n; i++) {
for(int j = 0; j < m; j++) {
int color = targetGrid[i][j];
if(colorRange.count(color)) {
colorRange[color][1] = min(colorRange[color][1], j);
colorRange[color][3] = max(colorRange[color][3], j);

colorRange[color][2] = i;
} else {
colorRange[color] = {i,j,i,j};
}
}
}
while(!colorRange.empty()) {
unordered_set<int> top;
for(auto [color, range]: colorRange) {
if(isOnTop(targetGrid, range, color)) {
top.insert(color);
}
}
if(top.empty()) return false;
for(auto tp : top) {
colorRange.erase(tp);
}

}
return true;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/03/07/PS/LeetCode/strange-printer-ii/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.