# what is the time complexity of an algorithm that uses a depth-first search to find the shortest path in a graph with n nodes and m edges?

### Mohammed

Guys, does anyone know the answer?

get what is the time complexity of an algorithm that uses a depth-first search to find the shortest path in a graph with n nodes and m edges? from screen.

## Shortest Path Algorithms Tutorials & Notes

Detailed tutorial on Shortest Path Algorithms to improve your understanding of Algorithms. Also try practice problems to test & improve your skill level.

## Shortest Path Algorithms

Problems Tutorial

The shortest path problem is about finding a path between

2

vertices in a graph such that the total sum of the edges weights is minimum.

This problem could be solved easily using **(BFS)** if all edge weights were (

1

), but here weights can take any value. Three different algorithms are discussed below depending on the use-case.

## Bellman Ford's Algorithm:

Bellman Ford's algorithm is used to find the shortest paths from the source vertex to all other vertices in a weighted graph. It depends on the following concept: Shortest path contains at most

n−1

edges, because the shortest path couldn't have a cycle.

So why shortest path shouldn't have a cycle ?

There is no need to pass a vertex again, because the shortest path to all other vertices could be found without the need for a second visit for any vertices.

**Algorithm Steps:**

The outer loop traverses from

0 : n−1 .

Loop over all edges, check if the next node distance > current node distance + edge weight, in this case update the next node distance to "current node distance + edge weight".

This algorithm depends on the relaxation principle where the shortest distance for all vertices is gradually replaced by more accurate values until eventually reaching the optimum solution. In the beginning all vertices have a distance of "Infinity", but only the distance of the source vertex =

0

, then update all the connected vertices with the new distances (source vertex distance + edge weights), then apply the same concept for the new vertices with new distances and so on.

**Implementation:**

Assume the source node has a number (

vector0 ):

int dis [1000 + 10];

for(int i = 0; i < m + 2; i++){

v[i].clear(); dis[i] = 2e9; }

for(int i = 0; i < m; i++){

scanf("%d%d%d", &from , &next , &weight);

v[i].push_back(from);

v[i].push_back(next);

v[i].push_back(weight);

} dis[0] = 0;

for(int i = 0; i < n - 1; i++){

int j = 0;

while(v[j].size() != 0){

if(dis[ v[j][0] ] + v[j][2] < dis[ v[j][1] ] ){

dis[ v[j][1] ] = dis[ v[j][0] ] + v[j][2];

} j++; } }

A very important application of Bellman Ford is to check if there is a negative cycle in the graph,

Time Complexity of Bellman Ford algorithm is relatively high

O(V⋅E) , in case E=V2 , O(V3) .

Let's discuss an optimized algorithm.

## Dijkstra's Algorithm

Dijkstra's algorithm has many variants but the most common one is to find the shortest paths from the source vertex to all other vertices in the graph.

**Algorithm Steps:**

Set all vertices distances = infinity except for the source vertex, set the source distance =

0 .

Push the source vertex in a min-priority queue in the form (distance , vertex), as the comparison in the min-priority queue will be according to vertices distances.

Pop the vertex with the minimum distance from the priority queue (at first the popped vertex = source).

Update the distances of the connected vertices to the popped vertex in case of "current vertex distance + edge weight < next vertex distance", then push the vertex

with the new distance to the priority queue.

If the popped vertex is visited before, just continue without using it.

Apply the same algorithm again until the priority queue is empty.

**Implementation:**

Assume the source vertex =

1 .

#define SIZE 100000 + 1

vector < pair < int , int > > v [SIZE]; // each vertex has all the connected vertices with the edges weights

int dist [SIZE]; bool vis [SIZE]; void dijkstra(){

// set the vertices distances as infinity

memset(vis, false , sizeof vis); // set all vertex as unvisited

dist[1] = 0;

multiset < pair < int , int > > s; // multiset do the job as a min-priority queue

s.insert({0 , 1}); // insert the source node with distance = 0

pairwhile(!s.empty()){

s.erase(s.begin());

int x = p.s; int wei = p.f;

if( vis[x] ) continue; // check if the popped vertex is visited before

vis[x] = true;

for(int i = 0; i < v[x].size(); i++){

int e = v[x][i].f; int w = v[x][i].s;

if(dist[x] + w < dist[e] ){ // check if the next vertex distance could be minimized

dist[e] = dist[x] + w;

s.insert({dist[e], e} ); // insert the next vertex with the updated distance

} } } }

Time Complexity of Dijkstra's Algorithm is

O(V2)

but with min-priority queue it drops down to

O(V+ElogV) .

However, if we have to find the shortest path between all pairs of vertices, both of the above methods would be expensive in terms of time. Discussed below is another alogorithm designed for this case.

## Floyd\u2013Warshall's Algorithm

Floyd\u2013Warshall's Algorithm is used to find the shortest paths between between all pairs of vertices in a graph, where each edge in the graph has a weight which is positive or negative. The biggest advantage of using this algorithm is that all the shortest distances between any

## Depth First Search (DFS) Algorithm

Depth First Search is a recursive algorithm for searching all the vertices of a graph or tree data structure. In this tutorial, you will learn about the depth-first search with examples in Java, C, Python, and C++.

## Depth First Search (DFS)

In this tutorial, you will learn about depth first search algorithm with examples and pseudocode. Also, you will learn to implement DFS in C, Java, Python, and C++.

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.

## Depth First Search Algorithm

A standard DFS implementation puts each vertex of the graph into one of two categories:

Visited Not Visited

The purpose of the algorithm is to mark each vertex as visited while avoiding cycles.

The DFS algorithm works as follows:

Start by putting any one of the graph's vertices on top of a stack.

Take the top item of the stack and add it to the visited list.

Create a list of that vertex's adjacent nodes. Add the ones which aren't in the visited list to the top of the stack.

Keep repeating steps 2 and 3 until the stack is empty.

## Depth First Search Example

Let's see how the Depth First Search algorithm works with an example. We use an undirected graph with 5 vertices.

Undirected graph with 5 vertices

We start from vertex 0, the DFS algorithm starts by putting it in the Visited list and putting all its adjacent vertices in the stack.

Visit the element and put it in the visited list

Next, we visit the element at the top of stack i.e. 1 and go to its adjacent nodes. Since 0 has already been visited, we visit 2 instead.

Visit the element at the top of stack

Vertex 2 has an unvisited adjacent vertex in 4, so we add that to the top of the stack and visit it.

Vertex 2 has an unvisited adjacent vertex in 4, so we add that to the top of the stack and visit it.

Vertex 2 has an unvisited adjacent vertex in 4, so we add that to the top of the stack and visit it.

After we visit the last element 3, it doesn't have any unvisited adjacent nodes, so we have completed the Depth First Traversal of the graph.

After we visit the last element 3, it doesn't have any unvisited adjacent nodes, so we have completed the Depth First Traversal of the 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.

DFS(G, u) u.visited = true

for each v ∈ G.Adj[u]

if v.visited == false

DFS(G,v) init() { For each u ∈ G u.visited = false For each u ∈ G DFS(G, u) }

## DFS Implementation in Python, Java and C/C++

The code for the Depth First Search Algorithm with an example is shown below. The code has been simplified so that we can focus on the algorithm rather than other details.

Python Java C C++

# DFS algorithm in Python

# DFS algorithm

def dfs(graph, start, visited=None):

if visited is None: visited = set() visited.add(start) print(start)

for next in graph[start] - visited:

dfs(graph, next, visited)

return visited

graph = {'0': set(['1', '2']),

'1': set(['0', '3', '4']),

'2': set(['0']), '3': set(['1']),

'4': set(['2', '3'])}

dfs(graph, '0')

## Complexity of Depth First Search

The time complexity of the DFS 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).

## Application of DFS Algorithm

For finding the path

To test if the graph is bipartite

For finding the strongly connected components of a graph

For detecting cycles in a graph

## Depth First Search or DFS for a Graph

A Computer Science portal for geeks. It contains well written, well thought and well explained computer science and programming articles, quizzes and practice/competitive programming/company interview Questions.

## Depth First Search or DFS for a Graph

Difficulty Level : Easy

Last Updated : 26 Dec, 2022

Read Discuss(110+) Courses Practice Video

Depth First Traversal (or Search) for a graph is similar to Depth First Traversal of a tree. The only catch here is, that, unlike trees, graphs may contain cycles (a node may be visited twice). To avoid processing a node more than once, use a boolean visited array. A graph can have more than one DFS traversal.

**Example:**

**Input:**n = 4, e = 6

0 -> 1, 0 -> 2, 1 -> 2, 2 -> 0, 2 -> 3, 3 -> 3

**Output:**DFS from vertex 1 : 1 2 0 3

**Explanation:**

DFS Diagram:

**Input:**n = 4, e = 6

2 -> 0, 0 -> 2, 1 -> 2, 0 -> 1, 3 -> 3, 1 -> 3

**Output:**DFS from vertex 2 : 2 0 1 3

**Explanation:**

DFS Diagram:

Recommended Problem DFS of Graph DFS Graph +2 more Accolite Amazon +2 more Solve Problem

Submission count: 1.4L

**Prerequisites:**See this post for all applications of Depth First Traversal.

Depth-first search is an algorithm for traversing or searching tree or graph data structures. The algorithm starts at the root node (selecting some arbitrary node as the root node in the case of a graph) and explores as far as possible along each branch before backtracking.

So the basic idea is to start from the root or any arbitrary node and mark the node and move to the adjacent unmarked node and continue this loop until there is no unmarked adjacent node. Then backtrack and check for other unmarked nodes and traverse them. Finally, print the nodes in the path.

Follow the below steps to solve the problem:

Create a recursive function that takes the index of the node and a visited array.

Mark the current node as visited and print the node.

Traverse all the adjacent and unmarked nodes and call the recursive function with the index of the adjacent node.

Below is the implementation of the above approach:

## C++

// C++ program to print DFS traversal from

// a given vertex in a given graph

#includeusing namespace std;

// Graph class represents a directed graph

// using adjacency list representation

mapclass Graph { public:

// function to add an edge to graph

void addEdge(int v, int w);

// DFS traversal of the vertices

// reachable from v void DFS(int v); };

void Graph::addEdge(int v, int w)

{

adj[v].push_back(w); // Add w to v’s list.

}

void Graph::DFS(int v)

{

// Mark the current node as visited and

// print it visited[v] = true; cout << v << " ";

// Recur for all the vertices adjacent

list// to this vertex

for (i = adj[v].begin(); i != adj[v].end(); ++i)

if (!visited[*i]) DFS(*i); } // Driver's code int main() {

// Create a graph given in the above diagram

Graph g; g.addEdge(0, 1); g.addEdge(0, 2); g.addEdge(1, 2); g.addEdge(2, 0); g.addEdge(2, 3); g.addEdge(3, 3);

cout << "Following is Depth First Traversal"

" (starting from vertex 2) \n";

// Function call g.DFS(2); return 0; }

// improved by Vishnudev C

## Java

## Python3

## C#

Java Python3 C# Javascript

**Output**

Following is Depth First Traversal (starting from vertex 2)

2 0 1 3

**Time complexity:**O(V + E), where V is the number of vertices and E is the number of edges in the graph.

**Auxiliary Space:**O(V), since an extra visited array of size V is required.

**Handling A Disconnected Graph:**

This will happen by handling a corner case.

The above code traverses only the vertices reachable from a given source vertex. All the vertices may not be reachable from a given vertex, as in a Disconnected graph. To do a complete DFS traversal of such graphs, run DFS from all unvisited nodes after a DFS. The recursive function remains the same.

Follow the below steps to solve the problem:

Create a recursive function that takes the index of the node and a visited array.

Mark the current node as visited and print the node.

Traverse all the adjacent and unmarked nodes and call the recursive function with the index of the adjacent node.

Run a loop from 0 to the number of vertices and check if the node is unvisited in the previous DFS, then call the recursive function with the current node.

Below is the implementation of the above approach:

## C++

// C++ program to print DFS

// traversal for a given

#include// graph

using namespace std;

class Graph {

Guys, does anyone know the answer?