0% found this document useful (0 votes)
61 views7 pages

BFS Ai

Uploaded by

abdul rahman
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
61 views7 pages

BFS Ai

Uploaded by

abdul rahman
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 7

BFS (Breadth-First Search) Algorithm in Artificial Intelligence

1. Definition:

• BFS is a search algorithm used to explore a graph or tree by visiting all nodes at the
current depth level before moving to the next level.

2. Process:

• Starts from a given node (called the root).

• Explores all its neighbors before moving to their children.

• Uses a queue (FIFO) to keep track of nodes to be visited.

3. Steps:

1. Enqueue the starting node.

2. Dequeue a node, mark it as visited, and print/explore it.

3. Enqueue all its unvisited neighbors.

4. Repeat until the queue is empty.

4. Key Properties:

• Complete: Guaranteed to find a solution if one exists.

• Optimal: Finds the shortest path in terms of number of edges (if all edges have equal
weight).

• Time Complexity: O(V + E), where V is the number of vertices and E is the number of
edges.

• Space Complexity: O(V), due to the storage of the queue.

5. Applications:

• Finding the shortest path in an unweighted graph.

• AI problems like puzzle solving, pathfinding in games.

BFS ensures systematic exploration, making it useful in scenarios where the shortest or shallowest
solution is desired.
Why BFS?

• Guarantees the shortest path: BFS will always find the shortest path in an unweighted
graph.

• Efficiency: It’s simple and avoids getting stuck in loops or taking unnecessarily long
routes.

This makes BFS ideal for scenarios like city navigation, network routing, and solving puzzles where the
shortest sequence of steps is crucial.

Why BFS is Used:

1. Un-weighted Graph: In this case, the roads don’t have specific distances (or all roads
have the same “cost”), so we are just interested in finding the route with the fewest number of
intersections.

2. Level-by-Level Exploration: BFS explores each intersection (node) level by level. It checks
all direct roads from the starting point, then moves to the next set of intersections. This guarantees that
the first time you reach your destination (Node G), you’ve done so using the shortest possible route (in
terms of number of roads).

Process:

• Start from Node A.

• Explore all intersections directly connected to Node A.

• For each of those intersections, explore the next set of intersections.

• Continue this process until the destination (Node G) is reached.


Since BFS explores nodes closest to the starting point first, it ensures that the first time you reach the
destination, you have found the shortest path.

Example: BFS in Shortest Path Finding

Scenario: Imagine you are in a city, and you want to find the shortest route from your location (Node A)
to a destination (Node G) using the city’s road network. Each road is represented as an edge, and
intersections are represented as nodes.

Program:-

graph ={

'5':['8','6'],

'8':['1','2'],

'6':['3','4'],

'1':[],

'2':[],

'3':[],

'4':[],

visited=[]

queue=[]

def bfs(visited,graph,node):

visited.append(node)

queue.append(node)

while queue:

m=queue.pop(0)
print(m,end=" ")

for neighbour in graph[m]:

if neighbour not in visited:

visited.append(neighbour)

queue.append(neighbour)

print("following is the breadth first search")

bfs(visited,graph,'5')

Program explanation line by line:-

This code implements the Breadth-First Search (BFS) algorithm on a graph using Python. Here is the line-
by-line breakdown and explanation of the functions used:

1. graph = {...}:

• A dictionary representing the graph where each key is a node, and the value is a list of
its neighbors (adjacent nodes). For example, node ‘5’ is connected to nodes ‘8’ and ‘6’. Nodes ‘1’, ‘2’, ‘3’,
and ‘4’ have no neighbors (empty lists).

• Function used: Dictionary data structure.

2. visited = []:

• An empty list to keep track of the nodes that have been visited during the BFS traversal.
This ensures that nodes are not visited more than once.

• Function used: List.

3. queue = []:

• An empty list to simulate a queue (FIFO - First In First Out) for keeping track of nodes to
be visited in the correct BFS order.

• Function used: List.

4. def bfs(visited, graph, node)::


• The definition of the bfs function, which performs the BFS traversal. It takes three
parameters:

• visited: The list of already visited nodes.

• graph: The graph to be traversed.

• node: The starting node for the BFS traversal.

5. visited.append(node):

• Adds the starting node to the visited list to mark it as visited.

• Function used: append function for the list.

6. queue.append(node):

• Adds the starting node to the queue to begin the BFS traversal.

• Function used: append function for the list.

7. while queue::

• A while loop that runs as long as there are elements in the queue. This loop controls the
BFS traversal process.

• Function used: while loop.

8. m = queue.pop(0):

• Removes the first element from the queue (FIFO behavior) and assigns it to m. This
element will be processed next.

• Function used: pop(0) to remove the first item from the list.

9. print(m, end=" "):

• Prints the node m (the current node being processed) without a newline. The end=" "
ensures that subsequent prints appear on the same line separated by spaces.

• Function used: print with end parameter.

10. for neighbour in graph[m]::

• A for loop that iterates over all the neighbors (adjacent nodes) of node m in the graph.

• Function used: for loop to iterate over a list.

11. if neighbour not in visited::


• A conditional check to see if the neighbor has already been visited. If not, it proceeds to
visit it.

• Function used: if statement with the in operator.

12. visited.append(neighbour):

• Adds the neighbor to the visited list to mark it as visited.

• Function used: append function for the list.

13. queue.append(neighbour):

• Adds the neighbor to the queue so that it can be processed in a future iteration of the
while loop.

• Function used: append function for the list.

14. print("following is the breadth first search"):

• Prints a message indicating the start of the BFS traversal.

• Function used: print.

15. bfs(visited, graph, '5'):

• Calls the bfs function with the arguments:

• visited: The list to track visited nodes.

• graph: The dictionary representing the graph.

• '5': The starting node for the BFS traversal.

• Function used: Function call.

Key Functions and Concepts:

• Lists (append, pop): Used for managing the visited nodes and the queue for BFS
traversal.

• Dictionaries: Used to represent the graph.

• Control structures: Loops (while, for) and conditionals (if) manage the flow of the BFS
algorithm.
This code performs a breadth-first traversal starting from node '5' and explores all its neighbors,
ensuring each node is visited once in the correct order.

You might also like