0% found this document useful (0 votes)
4 views8 pages

Breadth First Search

The document describes the implementation of Breadth First Search (BFS) and Depth First Search (DFS) algorithms in Python. It outlines the rules for traversing a graph using both methods, including the use of a queue for BFS and a stack for DFS. Example code and a sample graph are provided for both algorithms, demonstrating their successful implementation.
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
0% found this document useful (0 votes)
4 views8 pages

Breadth First Search

The document describes the implementation of Breadth First Search (BFS) and Depth First Search (DFS) algorithms in Python. It outlines the rules for traversing a graph using both methods, including the use of a queue for BFS and a stack for DFS. Example code and a sample graph are provided for both algorithms, demonstrating their successful implementation.
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1/ 8

Breadth First Search

AIM: Write a Program to Implement Breadth First Search using Python.


DESCRIPTION: Breadth First Search (BFS) algorithm traverses a graph in a breadthward
motion and uses a queue to remember to get the next vertex to start a search, when a dead end
occurs in any iteration.
Rule 1 − Visit the adjacent unvisited vertex. Mark it as visited. Display it. Insert
it in a queue.
Rule 2 − If no adjacent vertex is found, remove the first vertex from the queue.
Rule 3 − Repeat Rule 1 and Rule 2 until the queue is empty.

Step Traversal Description


1 Initialize the queue.

2 We start from visiting


S(starting node), and
mark it as visited.
3 We then see an
unvisited adjacent
node from S. In this
example, we have
three nodes but
alphabetically we
choose A, mark it as
visited and enqueue it.
4 Next, the unvisited
adjacent node from S
is B. We mark it as
visited and enqueue it.

5 Next, the unvisited


adjacent node from S
is C. We mark it as
visited and enqueue it.

6 Now, S is left with no


unvisited adjacent
nodes. So, we dequeue
and find A.

7 From A we have D as
unvisited adjacent
node. We mark it as
visited and enqueue it.
Code:
from collections import deque

def bfs(graph, start):


visited = set() # To keep track of visited nodes
queue = deque() # Initialize an empty queue
result = [] # To store the order of traversal

# Enqueue the starting node


queue.append(start)
visited.add(start) # Mark as visited

while queue:
# Dequeue the front element
current = queue.popleft()
result.append(current) # Process the node (e.g., store it in the
result)

# Enqueue all unvisited neighbors


for neighbor in graph[current]:
if neighbor not in visited:
visited.add(neighbor) # Mark neighbor as visited
queue.append(neighbor) # Enqueue the neighbor

return result

# Example Graph
graph = {
'A': ['B', 'C'],
'B': ['A', 'D', 'E'],
'C': ['A', 'F'],
'D': ['B'],
'E': ['B', 'F'],
'F': ['C', 'E']
}

# Perform BFS
start_node = 'A'
print("BFS Traversal:", bfs(graph, start_node))

Results: Breadth First Search using Python was successfully implemented.


Depth First Search
AIM: Write a Program to Implement Depth First Search using Python
DESCRIPTION: Depth First Search (DFS) algorithm traverses a graph in a depthward
motion and uses a stack to remember to get the next vertex to start a search, when a dead end
occurs in any iteration.
Rule 1 − Visit the adjacent unvisited vertex. Mark it as visited. Display it. Push it in a stack.
Rule 2 − If no adjacent vertex is found, pop up a vertex from the stack. (It will pop up all the
vertices from the stack, which do not have adjacent vertices.)
Rule 3 − Repeat Rule 1 and Rule 2 until the stack is empty.

Step Traversal Description


1 Initialize the stack.
2 Mark S as visited and
put it onto the stack.
Explore any unvisited
adjacent node from S.
We have three nodes
and we can pick any
of them. For this
example, we shall
take the node in an
alphabetical order.
3 Mark A as visited and
put it onto the stack.
Explore any unvisited
adjacent node from A.
Both Sand D are
adjacent to A but we
are concerned for
unvisited nodes only.

4 Visit D and mark it as


visited and put onto
the stack. Here, we
have B and C nodes,
which are adjacent to
D and both are
unvisited. However,
we shall again choose
in an alphabetical
order.
5 We choose B, mark it
as visited and put
onto the stack. Here
Bdoes not have any
unvisited adjacent
node. So, we pop
Bfrom the stack.

6 We check the stack


top for return to the
previous node and
check if it has any
unvisited nodes.
Here, we find D to be
on the top of the
stack.
7 Only unvisited
adjacent node is from
D is C now. So we
visit C, mark it as
visited and put it onto
the stack.

Code:
def dfs(graph, start):
visited = set() # To keep track of visited nodes
stack = [] # Initialize an empty stack
result = [] # To store the DFS traversal order

# Push the starting node onto the stack


stack.append(start)

while stack:
# Pop the top node from the stack
current = stack.pop()

if current not in visited:


visited.add(current) # Mark the node as visited
result.append(current) # Process the node (add to result)

# Push all unvisited neighbors onto the stack


for neighbor in reversed(graph[current]): # Reverse to maintain
order
if neighbor not in visited:
stack.append(neighbor)

return result
# Example Graph
graph = {
'A': ['B', 'C'],
'B': ['A', 'D', 'E'],
'C': ['A', 'F'],
'D': ['B'],
'E': ['B', 'F'],
'F': ['C', 'E']
}

# Perform DFS
start_node = 'A'
print("DFS Traversal:", dfs(graph, start_node))

Results: Depth First Search using Python was successfully implemented.

You might also like