Use app×
Join Bloom Tuition
One on One Online Tuition
JEE MAIN 2026 Crash Course
NEET 2026 Crash Course
CLASS 12 FOUNDATION COURSE
CLASS 10 FOUNDATION COURSE
CLASS 9 FOUNDATION COURSE
CLASS 8 FOUNDATION COURSE
0 votes
83 views
in Information Technology by (178k points)
What is the time complexity of BFS?

Please log in or register to answer this question.

1 Answer

0 votes
by (178k points)

The time complexity of BFS is O(V + E), where V is the number of vertices and E is the number of edges in the graph.

Example Code in Python:

from collections import defaultdict, deque

class Graph:
    def __init__(self):
        self.graph = defaultdict(list)

    def add_edge(self, u, v):
        self.graph[u].append(v)

    def bfs(self, start):
        visited = set()
        queue = deque([start])
        visited.add(start)

        while queue:
            node = queue.popleft()
            print(node, end=" ")

            for neighbor in self.graph[node]:
                if neighbor not in visited:
                    visited.add(neighbor)
                    queue.append(neighbor)

# Example usage:
g = Graph()
g.add_edge(0, 1)
g.add_edge(0, 2)
g.add_edge(1, 2)
g.add_edge(2, 0)
g.add_edge(2, 3)
g.add_edge(3, 3)

print("BFS Traversal starting from vertex 2:")
g.bfs(2)
 

Output:

BFS Traversal starting from vertex 2:
2 0 3 1 
 

This code demonstrates a basic implementation of BFS in Python for an adjacency list representation of the graph. It starts the traversal from vertex 2 and prints the BFS traversal order.

Welcome to Sarthaks eConnect: A unique platform where students can interact with teachers/experts/students to get solutions to their queries. Students (upto class 10+2) preparing for All Government Exams, CBSE Board Exam, ICSE Board Exam, State Board Exam, JEE (Mains+Advance) and NEET can ask questions from any subject and get quick answers by subject teachers/ experts/mentors/students.

Categories

...