Time complexity of BFS and DFS: O(V + E)
Time complexity of BFS and DFS: O(V + E)
Breadth-First Search (BFS) and Depth-First Search (DFS) are fundamental graph traversal algorithms used to explore nodes and edges in a graph.
BFS explores the graph level by level, starting from a given node. It uses a queue to keep track of the nodes to be explored next. As it visits each node, it adds its unvisited neighbors to the queue. 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. This is because BFS visits each vertex once and each edge once.
DFS explores the graph by going as deep as possible along each branch before backtracking. It uses a stack (either explicitly or through recursion) to keep track of the nodes to be explored next. Similar to BFS, DFS visits each vertex once and each edge once. Therefore, the time complexity of DFS is also O(V + E).
Example
Consider a graph with 5 vertices and 7 edges. Using BFS or DFS, the algorithms will visit each of the 5 vertices once and each of the 7 edges once, resulting in a total of 12 operations.
Remember this
Understanding the time complexity of BFS and DFS is crucial for analyzing the efficiency of algorithms used in graph-related problems, such as finding connected components, paths, and cycles in a graph.
Text adapted from Wikipedia, licensed under CC BY-SA 4.0.
Computational complexity of matrix multiplication
O(n³) naive matrix multiplication
Dijkstra's algorithm
Dijkstra's algorithm time complexity: O((V+E) log V)
BFS vs DFS: BFS finds shortest path in unweighted graphs, DFS uses less memory
BFS finds shortest path in unweighted graphs; DFS uses less memory
Binary search
How fast can you find a word in a dictionary?
non-convex loss landscapes are hard: many local minima and saddle points
Why do some hills have more tricky paths than others?
merge sort: O(n log n) always
Ever wondered why sorting your music library takes ages?
Swipe through 100 ML concepts daily
Open Pocket Polymath