1

I saw an implementation of breadth-first-search that's slightly different from what I've learned. What's the benefit of using three states "Unvisited, Visited, Visiting" for bfs? Or is it just a matter of taste?

Problem: find out whether there's a route between two nodes in a graph.

    public enum State {
        Unvisited, Visited, Visiting;
    } 

    public static boolean search(Graph g,Node start,Node end) {  
    LinkedList<Node> q = new LinkedList<Node>();
    for (Node u : g.getNodes()) {
        u.state = State.Unvisited;
    }
    start.state = State.Visiting;
    q.add(start);
    Node u;
    while(!q.isEmpty()) {
        u = q.removeFirst();
        if (u != null) {
            for (Node v : u.getAdjacent()) {
                if (v.state == State.Unvisited) {
                    if (v == end) {
                        return true;
                    } else {
                        v.state = State.Visiting;
                        q.add(v);
                    }
                }
            }
            u.state = State.Visited;
        }
    }
    return false;
}

Source: Gayle McDowell's Cracking the Coding Interview

Yi Qin
  • 11
  • 2
  • Visited / un visited is used in the calculation and can be implemented in many ways, the simplest being a Boolean. Other states has other uses such as graphic representation, See a simple example [here](https://stackoverflow.com/a/53853731/3992939) – c0der Jan 26 '21 at 05:50

0 Answers0