Skip to content

Commit f9e3720

Browse files
committed
Added c++ solution for 1500-1599 / 1591.Strange Printer II
1 parent 1da1fb7 commit f9e3720

File tree

1 file changed

+59
-0
lines changed

1 file changed

+59
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
class Solution {
2+
public:
3+
bool isPrintable(vector<vector<int>>& targetGrid) {
4+
int m = targetGrid.size(), n = targetGrid[0].size();
5+
6+
const int MAXC = 60;
7+
vector<bool> seen(MAXC+1,false);
8+
vector<int> minR(MAXC+1, m), maxR(MAXC+1, -1);
9+
vector<int> minC(MAXC+1, n), maxC(MAXC+1, -1);
10+
11+
for(int i=0;i<m;i++){
12+
for(int j=0;j<n;j++){
13+
int c = targetGrid[i][j];
14+
seen[c] = true;
15+
minR[c] = min(minR[c], i);
16+
maxR[c] = max(maxR[c], i);
17+
minC[c] = min(minC[c], j);
18+
maxC[c] = max(maxC[c], j);
19+
}
20+
}
21+
22+
vector<bitset<MAXC+1>> adj(MAXC+1);
23+
vector<int> indeg(MAXC+1,0);
24+
for(int c=1;c<=MAXC;c++){
25+
if(!seen[c]) continue;
26+
for(int i=minR[c]; i<=maxR[c]; i++){
27+
for(int j=minC[c]; j<=maxC[c]; j++){
28+
int d = targetGrid[i][j];
29+
if(d!=c && !adj[c].test(d)){
30+
adj[c].set(d);
31+
indeg[d]++;
32+
}
33+
}
34+
}
35+
}
36+
37+
// Kahn's algorithm on at most 60 nodes
38+
queue<int> q;
39+
int totalColors = 0;
40+
for(int c=1;c<=MAXC;c++){
41+
if(!seen[c]) continue;
42+
totalColors++;
43+
if(indeg[c]==0) q.push(c);
44+
}
45+
46+
int seenCount = 0;
47+
while(!q.empty()){
48+
int u = q.front(); q.pop();
49+
seenCount++;
50+
for(int v=1;v<=MAXC;v++){
51+
if(adj[u].test(v) && --indeg[v]==0){
52+
q.push(v);
53+
}
54+
}
55+
}
56+
57+
return seenCount == totalColors;
58+
}
59+
};

0 commit comments

Comments
 (0)