0% found this document useful (0 votes)
1K views9 pages

BFS and DFS Algorithm Pseudocode

Breadth first search is a recursive algorithm that traverses all nodes of a graph or tree data structure by exploring neighboring nodes first before moving to the next level neighbors. It has time complexity of O(V+E) where V is number of nodes and E is number of edges, and space complexity of O(V). It is used for applications like building search indexes, GPS navigation, and finding maximum flow in a network.
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)
1K views9 pages

BFS and DFS Algorithm Pseudocode

Breadth first search is a recursive algorithm that traverses all nodes of a graph or tree data structure by exploring neighboring nodes first before moving to the next level neighbors. It has time complexity of O(V+E) where V is number of nodes and E is number of edges, and space complexity of O(V). It is used for applications like building search indexes, GPS navigation, and finding maximum flow in a network.
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

Breadth first search

Traversal means visiting all the nodes of a graph. Breadth First Traversal or Breadth
First Search is a recursive algorithm for searching all the vertices of a graph or tree data
structure.

BFS pseudocode

BFS Algorithm Complexity


The time complexity of the BFS algorithm is represented in the form of O(V + E), where V is the
number of nodes and E is the number of edges.

The space complexity of the algorithm is O(V).

BFS Algorithm Applications


1. To build index by search index
2. For GPS navigation
3. Path finding algorithms
4. In Ford-Fulkerson algorithm to find maximum flow in a network
5. Cycle detection in an undirected graph
6. In minimum spanning tree algorithm

Depth First Search (DFS)


Depth first Search or Depth first traversal is a recursive algorithm for searching all the vertices of
a graph or tree data structure. Traversal means visiting all the nodes of a graph.

DFS Pseudocode (recursive implementation)


The pseudocode for DFS is shown below. In the init() function, notice that we run the DFS
function on every node. This is because the graph might have two different disconnected parts
so to make sure that we cover every vertex, we can also run the DFS algorithm on every node.

Dijkstra's Algorithm
Dijkstra's algorithm allows us to find the shortest path between any two vertices of a graph.

It differs from the minimum spanning tree because the shortest distance between two vertices
might not include all the vertices of the graph.

How Dijkstra's Algorithm works


Dijkstra's Algorithm works on the basis that any subpath B -> D of the shortest path A -> D
between vertices A and D is also the shortest path between vertices B and D.

Djikstra used this property in the opposite direction i.e we overestimate the distance of each
vertex from the starting vertex. Then we visit each node and its neighbors to find the shortest
subpath to those neighbors.

The algorithm uses a greedy approach in the sense that we find the next best solution hoping
that the end result is the best solution for the whole problem.

Djikstra's algorithm pseudocode


We need to maintain the path distance of every vertex. We can store that in an array of size v,
where v is the number of vertices.

We also want to be able to get the shortest path, not only know the length of the shortest path.
For this, we map each vertex to the vertex that last updated its path length.

Once the algorithm is over, we can backtrack from the destination vertex to the source vertex to
find the path.

A minimum priority queue can be used to efficiently receive the vertex with least path distance.

Dijkstra's Algorithm Complexity


Time Complexity: O(E Log V)

where, E is the number of edges and V is the number of vertices.

Space Complexity: O(V)

Dijkstra's Algorithm Applications


● To find the shortest path
● In social networking applications
● In a telephone network
● To find the locations in the map

Floyd-Warshall Algorithm
In this tutorial, you will learn how floyd-warshall algorithm works. Also, you will find working
examples of floyd-warshall algorithm in C, C++, Java and Python.

Floyd-Warshall Algorithm is an algorithm for finding the shortest path between all the pairs of
vertices in a weighted graph. This algorithm works for both the directed and undirected weighted
graphs. But, it does not work for the graphs with negative cycles (where the sum of the edges in
a cycle is negative).

Floyd-Warshall Algorithm

Floyd Warshall Algorithm Complexity


Time Complexity

There are three loops. Each loop has constant complexities. So, the time complexity of the
Floyd-Warshall algorithm is O(n3).

Space Complexity
The space complexity of the Floyd-Warshall algorithm is O(n2).

Floyd Warshall Algorithm Applications


● To find the shortest path is a directed graph
● To find the transitive closure of directed graphs
● To find the Inversion of real matrices
● For testing whether an undirected graph is bipartite

Kruskal's Algorithm
Kruskal's algorithm is a minimum spanning tree algorithm that takes a graph as input and finds
the subset of the edges of that graph which

● form a tree that includes every vertex


● has the minimum sum of weights among all the trees that can be formed from the graph

Kruskal Algorithm Pseudocode


Any minimum spanning tree algorithm revolves around checking if adding an edge creates a
loop or not.

The most common way to find this out is an algorithm called Union Find. The Union-Find
algorithm divides the vertices into clusters and allows us to check if two vertices belong to the
same cluster or not and hence decide whether adding an edge creates a cycle.

Kruskal's Algorithm Complexity


The time complexity Of Kruskal's Algorithm is: O(E log E)

Kruskal's Algorithm Applications


● In order to layout electrical wiring
● In computer network (LAN connection)

Prim's Algorithm
Prim's algorithm is a minimum spanning tree algorithm that takes a graph as input and finds the
subset of the edges of that graph which

● form a tree that includes every vertex


● has the minimum sum of weights among all the trees that can be formed from the graph

Prim's Algorithm pseudocode


The pseudocode for prim's algorithm shows how we create two sets of vertices U and V-U. U
contains the list of vertices that have been visited and V-U the list of vertices that haven't. One
by one, we move vertices from set V-U to set U by connecting the least weight edge.

Prim's vs Kruskal's Algorithm


Kruskal's algorithm is another popular minimum spanning tree algorithm that uses a different
logic to find the MST of a graph. Instead of starting from a vertex, Kruskal's algorithm sorts all
the edges from low weight to high and keeps adding the lowest edges, ignoring those edges
that create a cycle.

Prim's Algorithm Complexity


The time complexity of Prim's algorithm is O(E log V).

Prim's Algorithm Application


● Laying cables of electrical wiring
● In network designed
● To make protocols in network cycles

Ford-Fulkerson Algorithm
Ford-Fulkerson algorithm is a greedy approach for calculating the maximum possible flow in a
network or a graph.

A term, flow network, is used to describe a network of vertices and edges with a source (S)
and a sink (T). Each vertex, except S and T, can receive and send an equal amount of stuff
through it. S can only send and T can only receive stuff.

We can visualize the understanding of the algorithm using a flow of liquid inside a network of
pipes of different capacities. Each pipe has a certain capacity of liquid it can transfer at an
instance. For this algorithm, we are going to find how much liquid can be flowed from the source
to the sink at an instance using the network.

Terminologies Used
Augmenting Path

It is the path available in a flow network.


Residual Graph

It represents the flow network that has additional possible flow.

Residual Capacity

It is the capacity of the edge after subtracting the flow from the maximum capacity.

Ford-Fulkerson Applications
● Water distribution pipeline
● Bipartite matching problem
● Circulation with demands

Edmonds-Karp
• Same with Ford-Fulkerson, only differs in
finding the augmenting path
• Use BFS instead of DFS

Disjoint SET
KMP
O(m+n)
GRAHAM SCAN
complexity O(n log n).
Monotone Chain
Approach: Monotone chain algorithm constructs
the convex hull in O(n * log(n)) time. We have to
sort the points first and then calculate the upper
and lower hulls in O(n) time. The

Common questions

Powered by AI

The Floyd-Warshall algorithm is designed to compute shortest paths between all pairs of vertices and works correctly for graphs with negative weights but does not function properly if there are negative weight cycles, as it assumes no such cycles exist . In contrast, Dijkstra's algorithm cannot properly handle negative weight edges in a graph and hence will fail in the correct calculation of shortest paths under such conditions. Dijkstra's algorithm relies on consistently improving path estimates, which negative weights disrupt, leading to incorrect solutions .

Prim's algorithm has a time complexity of O(E log V) where E is the number of edges and V is the number of vertices . Meanwhile, Kruskal's algorithm has a time complexity of O(E log E). Although both algorithms have similar complexities in terms of sorting edge weights, Prim’s approach uses a priority queue which alters its efficient handling as the number of edges grows, whereas Kruskal’s focuses completely on sorting edge weights and utilizing a union-find data structure to detect cycles.

The choice between Prim's and Kruskal's algorithms often depends on the nature and structure of the network. Prim's algorithm is generally more efficient for dense graphs because it incrementally expands the MST by adding the nearest vertex, and uses a priority queue to handle edges, making it adaptive to dense scenarios . Conversely, Kruskal's algorithm can be preferable in sparse graphs due to its focus on global edge sorting and cycle detection using a union-find structure, which efficiently processes limited edges to form a minimal spanning tree . The density of the network, edge weights, and specific needs regarding cycle detection and edge management influence the algorithm choice in network design .

Prim's algorithm avoids cycles by maintaining a set of vertices already included in the Minimum Spanning Tree (MST) and progressively expands the MST by adding the lowest weight edge from any vertex in the MST to any vertex outside it . In contrast, Kruskal's algorithm avoids cycles by initially sorting all graph edges by weight and incrementally adding edges to the MST, ensuring that no edge creates a cycle by using the union-find data structure to check if adding an edge would connect two vertices already in the same tree cluster . Both strategies avoid cycles, but their approaches differ in whether they focus on vertices (Prim’s) or edges (Kruskal’s).

The efficiency and performance of BFS and DFS are significantly impacted by their underlying data structures. BFS utilizes a queue to manage the breadth-wise exploration, adding nodes to be explored from each layer before moving to the next, which ensures O(V + E) time complexity where V is vertices and E is edges . DFS uses a stack, usually implemented through recursion, to delve deeper into a node's children before backtracking, which inherently suits problems needing path explorations like maze or puzzle solutions. The queue allows BFS to systematically cover all nodes at a given depth, whereas the stack in DFS facilitates exhaustive exploration of paths, affecting their operational efficiency according to graph structure and required exploration strategy .

In the Ford-Fulkerson algorithm, the residual graph represents the remaining capacity of the network, taking into account the current flow assignments . It includes both the unutilized capacity in the direction of flow and the possible return flow for each edge. The algorithm repeatedly identifies augmenting paths—paths from the source to the sink in the residual graph—and adjusts flows until no more augmenting paths can be found. This iterative adjustment based on residual graphs helps optimize flow and ensures the calculation of the maximum possible flow in the network, exploiting the augmenting path for flow improvements .

The Floyd-Warshall algorithm can determine the transitive closure of a directed graph by using its iterative approach to calculate the reachability of vertices, initializing the reachability graph such that each vertex can reach itself. It then iteratively updates the path information by incorporating intermediate vertices. If vertex k is a potential intermediate step, and a path exists from i to k and k to j, then a path from i to j is inferred, effectively building a transitive closure. This process is repeated for all vertex pairs, ensuring reachability is reflected through intermediary connections . The algorithm’s systematic approach over all pairs ensures that any achievable connection, direct or through intermediates, is recorded, thus efficiently assuring transitive closure .

Dijkstra's algorithm determines the shortest path by initially overestimating the distances to all vertices and progressively minimizing these estimates. It selects the vertex with the smallest known distance, evaluates all its adjoining vertices, and updates their distances based on the central vertex's distance plus the edge weight . By consistently choosing the vertex with the minimum current distance and updating the shortest path estimates, it iteratively converges on the shortest path, relying on a greedy approach that ensures each subpath is also optimum, thus guaranteeing an optimal solution .

Dijkstra's algorithm is unsuitable for graphs with negative weight edges because it relies on the property that once a vertex's shortest path has been found and finalized, it will not need to be adjusted based on subsequent path explorations . Negative weight edges can lead to shorter paths being discovered after a vertex's shortest path seems to be finalized, thus undermining the algorithm's greedy approach and making it unable to reliably produce correct results. The presence of such edges would allow for adjustments beyond initial assumptions, leading to potentially invalid final shortest path calculations .

BFS (Breadth-First Search) visits all the vertices of a graph by moving across each connected component level by level, using a queue to keep track of the next node to be explored. This approach ensures that all vertices at the present depth are visited before moving onto vertices at the next depth level . In contrast, DFS (Depth-First Search) explores as far along a branch as possible before backtracking, employing a stack data structure (either explicitly or via recursion) to hold vertices yet to be explored. DFS continues down the path until there are no further vertices to be explored, then backs up and tries other paths .

You might also like