Skip to content

3500 3599 / 3530. Maximum Profit from Valid Topological Order in DAG #4397

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
Added c++ solution for 1500-1599 / 1591.Strange Printer II
  • Loading branch information
ZAID646 committed May 9, 2025
commit f9e372059964df1a342dc52233442f17a75eac0e
59 changes: 59 additions & 0 deletions solution/1500-1599/1591.Strange Printer II/Solutions.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
class Solution {
public:
bool isPrintable(vector<vector<int>>& targetGrid) {
int m = targetGrid.size(), n = targetGrid[0].size();

const int MAXC = 60;
vector<bool> seen(MAXC+1,false);
vector<int> minR(MAXC+1, m), maxR(MAXC+1, -1);
vector<int> minC(MAXC+1, n), maxC(MAXC+1, -1);

for(int i=0;i<m;i++){
for(int j=0;j<n;j++){
int c = targetGrid[i][j];
seen[c] = true;
minR[c] = min(minR[c], i);
maxR[c] = max(maxR[c], i);
minC[c] = min(minC[c], j);
maxC[c] = max(maxC[c], j);
}
}

vector<bitset<MAXC+1>> adj(MAXC+1);
vector<int> indeg(MAXC+1,0);
for(int c=1;c<=MAXC;c++){
if(!seen[c]) continue;
for(int i=minR[c]; i<=maxR[c]; i++){
for(int j=minC[c]; j<=maxC[c]; j++){
int d = targetGrid[i][j];
if(d!=c && !adj[c].test(d)){
adj[c].set(d);
indeg[d]++;
}
}
}
}

// Kahn's algorithm on at most 60 nodes
queue<int> q;
int totalColors = 0;
for(int c=1;c<=MAXC;c++){
if(!seen[c]) continue;
totalColors++;
if(indeg[c]==0) q.push(c);
}

int seenCount = 0;
while(!q.empty()){
int u = q.front(); q.pop();
seenCount++;
for(int v=1;v<=MAXC;v++){
if(adj[u].test(v) && --indeg[v]==0){
q.push(v);
}
}
}

return seenCount == totalColors;
}
};