Categories
Computer Science

BFS and DFS

(DSA – Tree Traversal)

BFSDFS
(Breadth First Search)(Depth First Search)
ParameterBFSDFS
Full FormBreadth First SearchDepth First Search
DefinitionBFS (Breadth First Search) is a graph traversal concept where nodes are traversed on same level before moving to next level.DFS (Depth First Search) is a graph traversal concept where nodes are traversed to depth until a node is reached with no unvisited neighbours.
Data StructureQueueStack
ConceptTree builds level by level.Tree builds sub-tree by sub-tree.
ApproachFirst In First Out (FIFO)Last In First Out (LIFO)
SourceBetter when target is closer to given source.Better when target is farther from given source.
ApplicationsBipartite Graphs, Shortest Path etc.Acyclic Graphs, Find Strongly Connected Components etc.
Python
#DFS and BFS
from collections import deque
# Define the graph
graph = {
'A': ['B', 'C'],
'B': ['A', 'D', 'E'],
'C': ['A', 'F'],
'D': ['B'],
'E': ['B', 'F'],
'F': ['C', 'E']
}
# BFS - Breadth First Search
def bfs(graph, start):
visited = {start}
queue = deque([start]) # FIFO: First In First Out
while queue:
node = queue.popleft() # return leftmost element
print(node, end=' ')
for neighbour in graph[node]:
if neighbour not in visited:
visited.add(neighbour)
queue.append(neighbour)
# DFS - Depth First Search
def dfs(graph, start):
visited = set()
stack = [start] # LIFO: Last In First Out
while stack:
node = stack.pop() # return rightmost element
if node not in visited:
print(node, end= ' ')
visited.add(node)
stack.extend(reversed(graph[node]))
print("BFS Traversal:")
bfs(graph, 'A') # Output: A B C D E F
print("\nDFS Traversal:")
dfs(graph, 'A') # Output: A B D E F C

V = number of vertices (nodes)

E = number of edges

Time and Space Complexity:

  • BFS: Complete, finds shortest path in unweighted graphs, O(V+E) time, O(V) space due to queue.
  • DFS: Not always complete without safeguards, may not find shortest path, O(V+E) time, space O(h) for recursion depth or O(V) for iterative stack.
  • BFS is slower and requires more memory space than DFS.
  • Choice depends on graph size, depth, and whether shortest path or memory efficiency is the priority.

Priyanka B.'s avatar

By Priyanka B.

Hello and welcome to my little corner of internet!! I am a techie. I am very interested to discover and innovate new advances in science and technology. Blogging is one of my hobbies which I think is very useful for broadening my knowledge horizons and help me grow my skills. Apart from blogging I have also little taste in artistic skills and literature, which can keep my writing and posts tangy.

Whether you stumbled in by chance or came here on purpose, I hope you find something that sparks your curiosity or makes you think a little deeper. Thanks for stopping by!!

Leave a comment