Depth-First Search (DFS) algorithm with Python

Yesterday (blogging every day now!) I have presented a visualization with Python, in which a simple and basic graph was displayed. Today, I have showed how to traverse it with DFS (Depth-First Search) with quite basic skills. Just for the sake of it, if we are talking about graphs and algorithms, time complexity and space complexity are to be mentioned:

  • Worst-case performance – O(|V| + |E|)
  • Worst-case space complexity – O(|V|)
  • Optimal? No!

The graph, used for the DFS search

In the video at the bottom of the article, DFS is explained with two different functions – dfs_minimal() and dfs_normal(). The minimal one only returns boolean value, stating whether the there is a road from the start node to the end node. And nothing else:

As that is probably not enough for almost any scenario, another DFS algorithm is implemented – returning the path to home, the nodes visited in order and the path length:

As you can see yourself, for the run of that algorithm, the node between F and P is removed:

DFS searches in depth, using LIFO. Think of it as it is the biggest optimist, who always thinks that the newest task is the best option to go for. Sometimes it works!

The GitHub code is here: https://github.com/Vitosh/Python_personal/tree/master/YouTube/048_Python-Graph

The YouTube video with the writing of the code is below:

Thank you and have a great day! 🙂

Tagged with: , , ,