Breadth-First and Depth-First Search

Pseudocode for BFS and DFS

BFS(G, s){
    Q.push(s) // a queue
    Mark s as visited // how?

    while(Q is not empty)
        u = Q.pop
        for each(v in adjList(u)){
             if(v not visited){ // how?
                Q.push(v)
                Mark v as visited //how?
            }
        }
    }
}


The version of DFS presented in the textbook:

DFS(G, s){
    S.push(s) // a stack

    while(S is not empty)
        u = S.pop
        if(u not visited){
            Mark u as visited
            for each(v in adjList(u)){
               S.push(v)
            }
        }
    }
}


A slightly optimized version of DFS that reduces the amount of redundant pushes:

DFS(G, s){
    S.push(s) // a stack

    while(S is not empty)
        u = S.pop
        if(u not visited){
            Mark u as visited
            for each(v in adjList(u)){
                 if(v not visited){
                    S.push(v)
                }
            }
        }
    }
}


A recursive version of DFS

DFS_Recursive(G, u){
    Mark u as explored
    for each(v in adjList(u)){
        if(v not explored){
            DFS_Recursive(G, v)
        }
}     

Differences between BFS and DFS: