Topological sort using BFS and DFS
// indegree = array indicating indegrees of each node 
// neighbors = a hashmap recording neighbors of each node 
// n = number of nodes 

for (int i = 0; i < n; i++) {
  if (indegree[i] == 0) q.add(i); 
}

while (!q.isEmpty()) {
	current = q.poll();  // the order by which we poll from queue is the sorted order 
	for (neighbor in neighbors[current]) {
		indegree[neighbor]--;
		if (indegree[neighbor] == 0) q.add(neighbor); 
	}
}
// cycle detection: at this point, if there is an element with indegree greater than 0, 
//                  we know that there is a cycle 
// visited = keeps track of nodes that are visited 
// neighbors = records neighbors of each node 

// LIFO order of stack will be the topologically sorted order 
Stack<Integer> stack = new Stack<>(); 

public void topologicalSort() {
	for (int node : nodes) {
		if (!visited[node]) dfs(node); 
	}
}

public void dfs(int node) {
	visited[node] = true;
	for (int neighbor : neighbors[node]) {
		if (!visited[neighbor]) dfs(neighbor); 
	}
	stack.push(node); 
}
Comments (0)