class Graph
{
private:
int V; // No. of vertices'
// Pointer to an array containing adjacency listsList
vector
vector
vector
int count;
public:
Graph(int _V)// Constructor
{
V = _V;
adj = vector
inDegree = vector
count = 0;
};
// function to add an edge to graph
void addEdge(int v, int w)
{
adj[w].push_back(v);
inDegree[v]++;
};
// prints a Topological Sort of the complete graph
void topologicalSort()
{
// find all in_degree==0, and mark them as visited(set inDegree to -1)
queue
for(int i=0; i
stack.push(i);
result.push_back(i);
inDegree[i]=-1; // maked as visited
count++;
}
}
// pop a node from queue, decrease the degree of the neighbours and push the degree==0
while(!stack.empty()){
int cur=stack.front();
stack.pop();
for(int i=0; i
if(inDegree[adj[cur][i]]==0){
count++;
stack.push(adj[cur][i]);
result.push_back(adj[cur][i]);
inDegree[adj[cur][i]]=-1;
}
}
}
};
vector
{
if(count==V) return result;
else return vector
}
};
class Solution {
public:
vector
Graph graph(numCourses);
vector
for(auto it = prerequisites.begin();it!=prerequisites.end();it++ )
graph.addEdge((*it).first,(*it).second);
graph.topologicalSort(); // sorting
result = graph.output();
return result;
}
};
No comments:
Post a Comment