Topological Sorting

LintCode Q 127 - Topological Sorting

Given an directed graph, a topological order of the graph nodes is defined as follow:

  • For each directed edge A -> B in graph, A must before B in the order list.
  • The first node in the order can be any node in the graph with no nodes direct to it.
  • Find any topological order for the given graph.

Challenge: Can you do it in both BFS and DFS?

Solution

Solution 1 : DFS

Definition for Directed graph.

class DirectedGraphNode {
	int label;
	ArrayList<DirectedGraphNode> neighbors;
	DirectedGraphNode(int x) { label = x; neighbors = new ArrayList<DirectedGraphNode>(); }
};

Code:

public ArrayList<DirectedGraphNode> topSort(ArrayList<DirectedGraphNode> graph) {
	ArrayList<DirectedGraphNode> res = new ArrayList<>();
	if (graph == null || graph.size() == 0) return res;

	Set<DirectedGraphNode> visited = new HashSet<>();

	for (DirectedGraphNode node: graph) 
		dfs(node, visited, res);

	return res;
}

private void dfs(DirectedGraphNode node, Set<DirectedGraphNode> visited, ArrayList<DirectedGraphNode> res) {

	if (visited.contains(node)) return;

	visited.add(node);
	for (DirectedGraphNode next: node.neighbors) {
		dfs(next, visited, res);
	}

	res.add(0, node);

	return;
}

Solution 2 : BFS / Topology Sorting

Code:

public ArrayList<DirectedGraphNode> topSort(ArrayList<DirectedGraphNode> graph) {
	ArrayList<DirectedGraphNode> res = new ArrayList<>();
	if (graph == null || graph.size() == 0) return res;

	int n = graph.size();
	int[] order = new int[n];
	for (DirectedGraphNode node: graph) {
		for (DirectedGraphNode next: node.neighbors) {
			order[next.label]++;
		}
	}

	Queue<DirectedGraphNode> que = new LinkedList<>();
	for (DirectedGraphNode node: graph) {
		if (order[node.label] == 0) que.offer(node);
	}

	while (!que.isEmpty()) {
		DirectedGraphNode curr = que.poll();
		res.add(curr);
		for (DirectedGraphNode next: curr.neighbors) {
			order[next.label]--;
			if (order[next.label] == 0) que.offer(next);
		}
	}

	return res;
}

   Reprint policy


《Topological Sorting》 by Tong Shi is licensed under a Creative Commons Attribution 4.0 International License
  TOC