Topological Sorting

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.

Example

For graph as follow:

picture

The topological order can be:

<code>[0, 1, 2, 3, 4, 5]
[0, 2, 3, 1, 5, 4]
...
</code>
Note

You can assume that there is at least one topological order in the graph.

Challenge

Can you do it in both BFS and DFS?

Solution 1. BFS

1. first create a map which contains all the nodes and its indegrees

2. only add node with 0 indegree to the list and once the node is select, remove 1 indegree from all its neighbors

public ArrayList<DirectedGraphNode> topSort(ArrayList<DirectedGraphNode> graph) {
    //BFS
    ArrayList<DirectedGraphNode> result = new ArrayList<>();
    if (graph == null || graph.size() <= 1) {
        return graph;
    }
    HashMap<DirectedGraphNode, Integer> inDegreeMap = new HashMap<>();
    for (DirectedGraphNode node : graph) {
        if (!inDegreeMap.containsKey(node)) {
            inDegreeMap.put(node, 0);
        }
        for (DirectedGraphNode neighbor : node.neighbors) {
            if (inDegreeMap.containsKey(neighbor)) {
                inDegreeMap.put(neighbor, inDegreeMap.get(neighbor) + 1);
            } else {
                inDegreeMap.put(neighbor, 1);
            }
        }
    }
    while (!inDegreeMap.isEmpty()) {
        for (DirectedGraphNode node : inDegreeMap.keySet()) {
            if (inDegreeMap.get(node) == 0) {
                result.add(node);
                inDegreeMap.remove(node);
                for (DirectedGraphNode neighbor : node.neighbors) {
                    inDegreeMap.put(neighbor, inDegreeMap.get(neighbor) - 1);
                }
                break;
            }
        }
    }
    return result;
}
FacebookTwitterGoogle+Share

Leave a Reply

Your email address will not be published. Required fields are marked *