Thursday, March 17, 2022

topological sorting in java

 package javaCodes;


import java.util.ArrayList;

import java.util.Iterator;

import java.util.Stack;


class graph

{

private int vertices;

private ArrayList<ArrayList<Integer> > abj;

public graph(int v)

{

this.vertices = v;

abj = new ArrayList<ArrayList<Integer> > (v);

for(int i=0; i<v; i++)

{

abj.add(new ArrayList<Integer> ());

}

}

void addedge(int u, int vertex)

{

abj.get(u).add(vertex);

}

void topologicalSort()

{

Stack<Integer> stack = new Stack<Integer> ();

boolean visited[] = new boolean[vertices];

for(int i=0; i<vertices; i++)

{

visited[i] = false;

}

for(int i=0; i<vertices; i++)

{

if(visited[i] != true)

{

topologicalSortUtil(i, visited, stack);

}

}

while(stack.empty() == false)

{

System.out.print(stack.pop() + "    " );

}

}


void topologicalSortUtil(int v, boolean[] visited, Stack<Integer> stack) {

visited[v] = true;

Iterator<Integer> ite = abj.get(v).iterator();

while(ite.hasNext())

{

int temp = ite.next();

if(!visited[temp])

{

topologicalSortUtil(temp, visited, stack);

}

}

stack.push(new Integer(v));

}

}


public class topological_sorting {

public static void main(String args[])

{

graph g = new graph(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);

System.out.print("topological sorting sequence is : ");

g.topologicalSort();

}


}


No comments:

Post a Comment