HiveBrain v1.2.0
Get Started
← Back to all entries
patterncppMinor

DFS and BFS in a graph in C++

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
andbfsdfsgraph

Problem

Here goes the depth first search:

#include 
#include 

using namespace std;

typedef vector > graph; // adjacency list, vertexs are integers

void dfs(graph g, int s0) // s0 is the first vertex in the search
{
    int n = g.size();

    if(s0 = n) // invalid initial vertex
        return;

    vector already_seen(n, false);
    vector to_be_handled {};

    to_be_handled.push_back(s0);

    while(to_be_handled.size() > 0)
    {
        int s = to_be_handled.back();
        to_be_handled.pop_back();

        if(!already_seen[s])
        {
            already_seen[s] = true;

            cout << s << " "; // handle s

            for(int v: g[s]) // add neighbors
                to_be_handled.push_back(v); // (*)
        }
    }
}


And for the breadth first search, just replace the line (*) with this line:

to_be_handled.insert(to_be_handled.begin(), v);


I guess using a queue would be more effective for the BFS but I initially just wanted to implement a DFS so don't mind the second one.

Solution

using namespace std is considered bad practice.

to_be_handled.insert(to_be_handled.begin(), v); will badly hurt the performance. As mentioned in comments, BFS benefits from using std::queue, which is specifically designed for this purpose.

Simulating stack with std::vector is also dubious, again from the performance point of view. std::vector guarantees contiguous storage, and the you'd have to face reallocation penalty as it grows. Again, std::stack is specifically designed to avoid such a penalty.

The utility of the function is severely limited by the handler being hardcoded. You may pass the handler as an argument, or better yet restructure the code to make them iterators of Graph, and let the client handle vertices, e.g.:

Graph g;
    for (auto it: g.bfs_iterator(start)) {
        handle(it);
    }

Code Snippets

Graph g;
    for (auto it: g.bfs_iterator(start)) {
        handle(it);
    }

Context

StackExchange Code Review Q#162551, answer score: 2

Revisions (0)

No revisions yet.