Home > Software engineering >  Why do we need DFS or BFS algorithms for graphs?
Why do we need DFS or BFS algorithms for graphs?

Time:01-15

enter image description here

I used list implementation to create a graph. However, I don't get why we need to perform a breath-first with queue or depth-first with stack to reach all nodes because when we use this implementation, we can reach all nodes.

For example, in this photo, I can do that

struct Node* temp = A;
while(temp != NULL)
{
 //do something
 temp = temp->next;
}

CodePudding user response:

You don't need a BFS or DFS search to visit all nodes of a graph. Those are tree traversal algorithms. If your graph isn't (just) stored as a tree, you wouldn't use an algorithm to visit it like a tree.


As an aside, your approach is a BFS and a DFS! A linked list is really just a unary tree, and the approach you describe performs both a DFS and BFS of it.

  • Related