🎉 One-stop destination for all your technical interview Preparation 🎉
class Solution {
public:
bool isPossible(int V, vector<pair<int, int>>& prerequisites)
{
vector<int> adj[V];
for (auto it : prerequisites) {
adj[it.first].push_back(it.second);
}
vector<int> inDegree(V, 0);
for (int i = 0; i < V; i++) {
for (auto it : adj[i]) {
inDegree[it]++;
}
}
queue<int> q;
for (int i = 0; i < V; i++) {
if (inDegree[i] == 0) {
q.push(i);
}
}
vector<int> topo;
while (!q.empty()) {
int node = q.front();
q.pop();
topo.push_back(node);
// node in topo so decrease it from indegree
for (auto it : adj[node]) {
inDegree[it]--;
if (inDegree[it] == 0) {
q.push(it);
}
}
}
return topo.size() == V;
}
};
class Solution {
public:
vector<int> findOrder(int V, int m, vector<vector<int>> prerequisites)
{
vector<int> adj[V];
for (auto it : prerequisites) {
adj[it[1]].push_back(it[0]); // here relationship is reverse of course schedule 1
}
vector<int> inDegree(V, 0);
for (int i = 0; i < V; i++) {
for (auto it : adj[i]) {
inDegree[it]++;
}
}
queue<int> q;
for (int i = 0; i < V; i++) {
if (inDegree[i] == 0) {
q.push(i);
}
}
vector<int> topo;
while (!q.empty()) {
int node = q.front();
q.pop();
topo.push_back(node);
// node in topo so decrease it from indegree
for (auto it : adj[node]) {
inDegree[it]--;
if (inDegree[it] == 0) {
q.push(it);
}
}
}
if (topo.size() == V)
return topo;
return {};
}
};