What is the difference between DFS and BFS? Where can I apply each?

DFS, or Depth First Search traverses a graph - which is any set of interconnected nodes 'depth first'. It tries to go all the way to the end, and if it fails returns back to the last intersection that it didn't try. BFS, or Breadth First Search, traverses a graph by only going to the next set of nodes from it's current set. In effect it goes to all the nodes of distance one from the starting node, and in the next step goes to all nodes 2 from the starting node. The applications of each depend heavily on the use case. If the nodes we were looking for are deep in the graph, using BFS could be impractical as it could potentially take a long time. If solutions are rare, and can be anywhere in the graph, BFS would be significantly faster than DFS. DFS also has the added advantage of giving metrics such as shortest distance from the starting point, meanwhile the same metric in DFS would be harder to implement.

TD

Related Python Mentoring answers

All answers ▸

Explain how python programs are structured and give an example of how methods are initiated


Create an rock, paper, scissors game. The user should input one option, and the computer should play randomly.


Write a Python script to take a product name as input and then automatically google search reviews for it and open the top 3 search results in different tabs


Write a simple Python program that asks a user to input their age and name and then return the text: "Hi my name is *NAME*, and I am *AGE* years old."