Topological sort is an basic topic in graph theory, which is the foundation for many other problems like calculating strongly connected components (SCC). This article will discuss a couple of problems related to topological sort and its application. I will keep updating this article to include more problems in the future.
Leetcode 207. Course Schedule
Leetcode 269. Alien Dictionary
\newline
\newline
\newline
Leetcode 207. Course Schedule
This problem is a simple application for topological sort. Each course can be treated as a graph node and prerequisites can be treated as edges. There are two popular way of implementing topological sort, DFS based and BFS based implementations. I will have a discussion about their details.
The following is the DFS based implementation
// DFS based algorithm
class Solution {
//private int idx;
//private int[] toposort;
public boolean canFinish(int numCourses, int[][] prerequisites) {
/**
* Use an arry of Set is convenient if the nodes are continuous numbers.
* If the node is a string or other thing, we can also use a Map<String, Set<String>>
*/
Set<Integer>[] g = new Set[numCourses];
for (int[] edge : prerequisites) {
if (g[edge[1]] == null) {
g[edge[1]] = new HashSet<Integer>();
}
g[edge[1]].add(edge[0]);
}
//toposort = new int[numCourses];
//idx = toposort.length - 1;
int[] state = new int[numCourses];
for (int i = 0; i < numCourses; ++i) {
if (state[i] == 0 && !dfs(i, state, g)) {
return false;
}
}
return true;
}
/**
* There are three states here:
* 0 means the node is not visited yet.
* 1 means the node is currently in use, in other words, it is currently on
* the recursion stack. If the neighbor nodes have edges pointing to nodes in recursion statck,
* then that produces a cycle.
* 2 means the node have finished visiting all of its neighbor nodes.
*/
private boolean dfs(int u, int[] state, Set<Integer> g[]) {
state[u] = 1;
if (g[u] != null) {
for (