0% found this document useful (0 votes)
10 views3 pages

Eadth First Search Algorithm

2.BREADTH FIRST SEARCH ALGORITHM2.BREADTH FIRST SEARCH ALGORITHM b

Uploaded by

athulskrishnan6
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)
10 views3 pages

Eadth First Search Algorithm

2.BREADTH FIRST SEARCH ALGORITHM2.BREADTH FIRST SEARCH ALGORITHM b

Uploaded by

athulskrishnan6
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/ 3

Date :17/11/2024

2. BREADTH FIRST SEARCH


ALGORITHM

AIM: Python program to implement Breadth First Search Algorithm.

PROBLEM DESCRIPTION: A standard BFS implementation puts each vertex of the graph into one
of two categories: Visited and Not Visited.The purpose of the
algorithm is to mark each vertex as visited while avoiding cycles.

ALGORITHM:

1. Define a sample graph as a dictionary, where keys are vertices, and values are lists of
adjacent vertices.
2. Call the bfs function with the graph and starting vertex (0).
3. Define two containers:
 visited: A set to keep track of visited vertices to avoid revisiting them.
 queue: A deque (double-ended queue) to implement the BFS exploration.
4. Add the root vertex to both visited and queue.
5. Create a loop that continues as long as the queue is not empty
i. Dequeue a vertex from the front of the queue.
ii. Print the vertex to show the traversal order.
iii. Iterate through all neighbors of the dequeued vertex in the graph.
▪ If a neighbor is not yet in the visited set, Add the neighbor to both visited and queue.

PROGRAM:

import
collections #
BFS algorithm

def bfs(graph, root):


visited, queue = set(),
collections.deque([roo
t]) visited.add(root)

while queue:
# Dequeue a vertex from queue
vertex = queue.popleft()
print(str(vertex) + " ", end="")

# If not visited, mark it as visited, and enqueue it


for neighbour in graph[vertex]:
if neighbour not in visited:
visited.add(neighbour)
queue.append(neighbour)
if name == ' main ':
graph = {0: [1, 2, 3], 1: [0, 2], 2: [0, 1, 4], 3: [0], 4:[2]}
print("Following is Breadth First Traversal: ")
bfs(graph, 0)

OUTPUT:

RESULT: The above Program was implemented and verified successfully

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy