Topology Sort

Topology Sort

  1. BFS

    1. Use Map to store the flowing times of each node

    2. Use Queue to store the initial node of graph

    3. A node is added when its all sources are traversed

/**
 * Definition for Directed graph.
 * class DirectedGraphNode {
 *     int label;
 *     ArrayList<DirectedGraphNode> neighbors;
 *     DirectedGraphNode(int x) { label = x; neighbors = new ArrayList<DirectedGraphNode>(); }
 * };
 */

public class Solution {
    /*
     * @param graph: A list of Directed graph node
     * @return: Any topological order for the given graph.
     */
    public ArrayList<DirectedGraphNode> topSort(ArrayList<DirectedGraphNode> graph) {
        Map<DirectedGraphNode, Integer> map = new HashMap<>();

        // Count the flow in number of each node 
        for (DirectedGraphNode node: graph){
            for (DirectedGraphNode neighbor: node.neighbors){
                map.put(neighbor, map.getOrDefault(neighbor, 0) + 1);
            }
        }

        ArrayList<DirectedGraphNode> ans = new ArrayList<>();
        Queue<DirectedGraphNode> queue = new LinkedList<>();
        // Find the heads of graph
        for (DirectedGraphNode node: graph){
            if (!map.containsKey(node)){
                queue.add(node);
                ans.add(node);
            }
        }

        // start to put node to ans
        while(!queue.isEmpty()){
            DirectedGraphNode curNode = queue.poll();
            for (DirectedGraphNode node: curNode.neighbors){
                map.put(node , map.get(node) - 1);
                if (map.get(node) == 0){
                   queue.add(node);
                   ans.add(node);
                }
            }
        }
        return ans;
    }
}
  1. DFS

    1. Use map to record the flowing in times of each node

    2. Find out the initial node of graph and put them into stack

    3. A boolean array to record "traversed"

    4. Use dfs and a stack to push leaf node first, parent node last

210 Course Schedule

There are a total of n courses you have to take, labeled from 0 to n - 1.

Some courses may have prerequisites, for example to take course 0 you have to first take course 1, which is expressed as a pair: [0,1]

Given the total number of courses and a list of prerequisite pairs, is it possible for you to finish all courses?

269 Alien Dictionary

E.g.

    1. Similar to topology sort, 但比較對象變成word to word 第一個發生變化的char

    2. 若char已經比較過則不允許增加degree,注意 if condition 後break的時機

Last updated