Write an algorithm to implement depth-first search. How is depth-first search different from Breadth-first search? Also, write any two applications of complete graph.


Q.) Write an algorithm to implement depth-first search. How is depth-first search different from Breadth-first search? Also, write any two applications of complete graph.

Subject: Data Structure and Algorithm

Algorithm for Depth-first Search:

Input: Graph G = (V, E), where V is the set of vertices and E is the set of edges. Additionally, a starting/root vertex v is chosen.

Output: A traversal of the graph starting from the root vertex v, visiting each vertex exactly once.

Procedure:

  1. Initialize:

    • Create an empty stack S.
    • Mark all vertices as unvisited.
  2. Push the starting vertex v onto the stack S:

    • Mark the starting vertex as visited.
  3. While the stack S is not empty:

    • Pop the top vertex, denoted as u, from the stack S.
  4. For each unvisited adjacent vertex w of u:

    • Mark w as visited.
    • Push w onto the stack S.
  5. Repeat steps 3 and 4 until the stack S is empty:

    • This ensures that all vertices and edges are visited exactly once.

Time Complexity:

  • In the worst case, the time complexity of depth-first search is O(V + E), where V is the number of vertices and E is the number of edges in the graph.

Difference between Depth-first Search and Breadth-first Search:

Depth-first Search:

  • Explores a single branch as far as possible before backtracking.
  • It follows the "last in, first out" (LIFO) principle, similar to a stack data structure.

Breadth-first Search:

  • Explores all adjacent nodes at the current level before moving to the next level.
  • It follows the "first in, first out" (FIFO) principle, similar to a queue data structure.

Applications of Complete Graph:

1. Traveling Salesman Problem (TSP):

  • A complete graph is used to represent the distances between cities in the TSP.
  • The goal is to find the shortest Hamiltonian cycle (a cycle that visits every vertex exactly once) in the complete graph to determine the optimal route for the traveling salesperson.

2. Network Routing:

  • A complete graph is used to model a network, where vertices represent network nodes and edges represent connections between nodes.
  • Routing algorithms, such as Dijkstra's algorithm or Floyd-Warshall algorithm, use the complete graph to find the shortest paths between nodes in the network.