For Java: Goals: Work with graph data structures and worklists. Implement the in
ID: 3824315 • Letter: F
Question
For Java:
Goals: Work with graph data structures and worklists.
Implement the in-degree based version of the Topological Sort algorithm.
Take as input a list of vertices and a list of edges for a directed graph.
Create the adjacency list representation, storing the outlist and the indegree for each vertex. (Count the vertices as you do so.) Set the label for the next vertex to 0.
Traverse the vertex headers in the adjacency list, placing any vertex with indegree 0 on a worklist (use a queue).
While the worklist is not empty: remove the top vertex, give it the current label, and increment the next_label. Traverse its adjacency list, decrementing the indegree of each of its out-neighbors. If an indegree becomes zero, add that vertex to the worklist.
If next_label == the number of vertices, report the topological labeling in numerical order. If not, report that there is a cycle
Explanation / Answer
#include<iostream>
#include <list>
#include <stack>
using namespace std;
class Graph
{
int V;
list<int> *adj;
void topologicalSortUtil(int v, bool visited[], stack<int> &Stack);
public:
Graph(int V); // Constructor
void addEdge(int v, int w);
void topologicalSort();
};
Graph::Graph(int V)
{
this->V = V;
adj = new list<int>[V];
}
void Graph::addEdge(int v, int w)
{
adj[v].push_back(w);
}
void Graph::topologicalSortUtil(int v, bool visited[],
stack<int> &Stack)
{
visited[v] = true;
list<int>::iterator i;
for (i = adj[v].begin(); i != adj[v].end(); ++i)
if (!visited[*i])
topologicalSortUtil(*i, visited, Stack);
Stack.push(v);
}
void Graph::topologicalSort()
{
stack<int> Stack;
bool *visited = new bool[V];
for (int i = 0; i < V; i++)
visited[i] = false;
for (int i = 0; i < V; i++)
if (visited[i] == false)
topologicalSortUtil(i, visited, Stack);
while (Stack.empty() == false)
{
cout << Stack.top() << " ";
Stack.pop();
}
}
int main()
{
Graph g(6);
g.addEdge(5, 2);
g.addEdge(5, 0);
g.addEdge(4, 0);
g.addEdge(4, 1);
g.addEdge(2, 3);
g.addEdge(3, 1);
cout << "Following is a Topological Sort of the given graph ";
g.topologicalSort();
return 0;
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.