Kahn's Topological Sort Algorithm Theory And Implementation In Java:-
In Graph Theory Kahn's Algorithm is used to Solve Topological Sort problem in this algorithm we use BFS and Queue to solve this problem
1) Kahn's Algorithm is Used to solve Topological Sort Problem
2) Kahn's Algorithm Only Apply On DAG
3) DAG has at least one vertex whose in degree is 0 and at least one vertex whose out degree is zero
the vertex whose in degree is zero means that vertex is not dependent on any other vertex and we can start topological sorting with this vertex.
we will use in degree array to solve this problem
watch this video to know more about Kahn's Algorithm
After Watching above video i hope you have better understanding about Kahn's algorithm . first try yourself to implement this logic if you are unable to implement then watch this video :
After watching this above video you are able to implement it if no then full java code is below you can see
but please don't copy paste
class Edge
{
int source, dest;
public Edge(int source, int dest) {
this.source = source;
this.dest = dest;
}
}
import java.util.ArrayList;
import java.util.List;
class Graph
{
// A List of Lists to represent an adjacency list
public List<List<Integer>> adjList = null;
// stores indegree of a vertex
public int []indegree;
// Constructor
Graph(List<Edge> edges, int N) {
adjList = new ArrayList<>();
for (int i = 0; i < N; i++) {
adjList.add(new ArrayList<>());
}
indegree = new int[N];
// add edges to the undirected graph
for (Edge edge: edges)
{
// add an edge from source to destination
adjList.get(edge.source).add(edge.dest);
// increment in-degree of destination vertex by 1
indegree[edge.dest]++;
}
}
}
0 Comments