Question

I am reading the materials related to graph in Data Structures and Algorithms in C++ 4e(By Adam Drozdek). In his implementation of Graph Breadth First Search, the psuedo code is like:

BFS():
    for all vertices u
        num(u) = 0
    edges = null
    i = 1
    while there is a vertex v such that num(v) is 0
        num(v)++
        enqueue(v)
        while queue is not empty
            v = dequeue()
            if num(u) is 0
                num(u) = i++
                enqueue(u)
                attach edge(v,u) to edges
    output edges

Basically, in the implementation of graph, we already keep a set of all vertices and a set of all edges. In BFS, the algorithm first enumerate every vertex not visited in this set to traverse the complete graph.

My question is: since we already store all the vertex in a set, we can loop through the set to operate on a particular vertex without using BFS algorithm. Why do we need a graph traversal algorithm and what is main use?

Was it helpful?

Solution

There are many uses for BFS and DFS...
To give you an idea for BFS:

  1. You have a graph representing a social network and want to make friend suggestions for a particular user. Then, you do a BFS. The closer the vertices (people), the better rank in the friends suggestion list. (If the number of users is large, it makes sense to stop at a distance of 3 and not do the BFS on the entire graph).

  2. Solution space searching. Extremely useful when the solution space is infinite. (see Game Trees)

  3. Shortest paths (if the edges have the same weight and there are no loops). Dijkstra adapted it to work for variable weights (see Dijkstra's algorithm).

OTHER TIPS

For instance, typically DFS is implicitly used when a tree is traversed recursively.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top