# BFS vs DFS Graph Search Algorithms in Python

Here are implementations of iterative BFS and DFS search algorithms in Python.

These are just to illustrate the slight difference in implementation of these algorithms.

Basically, if you want to go deep, with DFS, you can use a queue on which you’ll be adding the next elements to explore as you traverse the graph.
If you want to scan around the current node, you can use a stack so that you keep looking at the closest elements before you move forward.

These functions use and return a list of visited nodes. If you want to make this a little more efficient, you can mark nodes as visited using a dictionary, or if the nodes themselves can have a property added to them, you can use that instead so you don’t have to do a linear search every time you want to know if a node was visited or not. I left it like that again, to just focus on the algorithm itself and not in the performance optimizations.

Source

Output

This site uses Akismet to reduce spam. Learn how your comment data is processed.

1. Forgive me if I’m mistaken, but I don’t think your BFS works properly. BFS should return the shorted path, in your first example DFS returns a shorter path than BFS, that’s impossible.

I need to look at this again, wrote it a long time ago.
But your assumption based on the length of the paths has nothing to do with the correctness. Results may vary depending on the graph topology right?

However, you may have drawn the graph and seen an error 🙂

3. Samuel

James it’s right. If you implement BFS to go from A to B, it will give you the shortest path because BFS computes in layers.

Note that for that given graph you do not have a 2-3 connection (for exemple), so [1, 2, 3, 4, 5, 6, 7] can never be a path from the graph.

4. maja

I have the following error when i open it in python shell:

BFS Path Source:

Traceback (most recent call last):
File “…”, line 43, in
print “BFS Path”,BFS(1,7,GRAPH)
File “…”, line 5, in BFS
print “Source:”,source,”Target:”,target
NameError: global name ‘source’ is not defined

Why?