Traversing - BFS, DFS & More
Breadth-First Search
In the previous section, remember printAll() function?
We will be traversing just like that but a different approach. In breadth first, imagine you are a dragon and you are breathing fire in a wood, LOL. So which trees are gonna burn first?
Ovbiously the closer ones, right?
In the breadth first, we are gonna use queue to make a structure from a specific node, add it's adjacent nodes and process the front element one by one. Preety interesting right?
Instead of writing a brand new code, let' tweak our sweet little code from previous one, we can actually change the core structure and add a new variable named
status, which will indicate we have visited that or not. In this way,class Node { public: int data; bool status; Node* next_link; Node* adjacent; Node* destination; Node (int data) { this->data = data; this->next_link = NULL; this->adjacent = NULL; this->destination = NULL; this->status = false; } Node (Node* destination) { this->data = 0; this->next_link = NULL; this->adjacent = NULL; this->destination = destination; this->status = false; } };Here
truemeans we have visited the node. Let's talk about it (code) after DFS.
Depth-First Search
In DFS, instead of queue, we are going to use stack. That's the difference. I think you can figure out the rest.
And if I complete the code with BFS, our whole code will be,
In the above code, we are directly tweaking the memory of main class Node, and so our visited value will be changed after one BFS or DFS. So we can't use both BFS and DFS at the same time. So what to do?
BFS + DFS
In this case, (above warning) we can actually go ahead and use separate map (STL lib) for both BFS and DFS. Let's check the code,
And finally, with the support of STL, we can even write more beautiful codes like this, without worrying about implementing two tables separately. In the above cases, we started from the start point. But we can actually start the DFS and BFS algorithm from any point, and this is the most interesting thing about these two brothers.
Topological Sorting
In this case we will work on a directed graph without cycles. In this scenario, we will print the value which comes first before an another node while going through the order. Imagine in this way, nodes with 0 in-order nodes will come at the very last position, because we can't go from them to anywhere else!
We will basically focus on this particular thing (inorder nodes) and store the data in a queue. And optionally we can reverse the print order for natural view!
Here's a bonus algorithm, that may come handy. It will display the distance between a node to the rest! Feel free to explore further.
Single Source Shortest Path (SSSP)
Last updated
Was this helpful?