How do you fill up a directed depth first search with the time which came and time at which it left?

StackOverflow https://stackoverflow.com/questions/20140110

Вопрос

How do you fill up a directed depth first search with the time which came and time at which it left? Does it matter whether its direct or undirected for DFS?

for example

enter image description here

Это было полезно?

Решение

You simply keep a counter and assign-and-increase it each time you start and finish the DFS on a node. As the node to choose for starting the DFS of your picture (as it visits all the nodes in the graph and not just the ones connected to the U node), you would have to create a fake node that is connected to all the nodes in the graph and call the DFS on that node.

int time = 0;
HashSet<Vertex> visited = new HashSet<>();

DFS(Vertex v){
    v.start = time++;
    v.end = Integer.MAX_VALUE;
    for(Vertex t : v.neighbors){
        if(!visited.contains(t)){
            visited.add(t);
            DFS(t)
        }
        else if(t.start < v.start && t.end < v.start)
            //cross edge
        else if(t.start < v.start)
            //back edge
        else if(t.start > v.start)
            //forward edge

    }
    v.end = time++;
}
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top