NOIDATUT FREE E LEARNING PLATFORM • AKTU B.TECH

Depth First Search and Breadth First Search

Depth First Search (DFS) explores as deep as possible along each branch before backtracking, using a stack (or recursion). Breadth First Search (BFS) explores all neighbor nodes at the present depth prior to moving on to the nodes at the next depth level.


Theory & Explanation

Graph Traversal Algorithms: Depth First Search (DFS) and Breadth First Search (BFS)

DFS and BFS are fundamental algorithms used to traverse or search through the vertices (nodes) and edges of a graph or tree data structure. They systematically visit all nodes within a connected component.

1. Graphical Representation (Example Graph)

We will use the following undirected, unweighted graph to demonstrate both traversal algorithms, starting from vertex A.

A
B
C
D
E
F

Undirected Graph Structure

2. Depth First Search (DFS)

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

Key Characteristics

  • Strategy: "Go deep, then backtrack."
  • Data Structure: Stack (LIFO - Last-In, First-Out). Usually implemented using recursion (function call stack).
  • Use Cases: Finding paths, topological sorting, detecting cycles, solving mazes, generating components.

Example Walkthrough (Starting at A, visiting neighbors alphabetically)

  1. Visit A. Stack: [A]. Visited: {A}.
  2. Move to A's first unvisited neighbor, B. Visit B. Stack: [A, B]. Visited: {A, B}.
  3. Move to B's first unvisited neighbor, E. Visit E. Stack: [A, B, E]. Visited: {A, B, E}.
  4. E has no unvisited neighbors. Backtrack to B. Backtrack to A.
  5. Move to A's next unvisited neighbor, C. Visit C. Stack: [A, C]. Visited: {A, B, E, C}.
  6. Move to C's first unvisited neighbor, F. Visit F. Stack: [A, C, F]. Visited: {A, B, E, C, F}.
  7. F has no unvisited neighbors. Backtrack to C.
  8. Move to C's next unvisited neighbor, D. Visit D. Stack: [A, C, D]. Visited: {A, B, E, C, F, D}.
  9. All reachable nodes visited.

DFS Traversal Output: A → B → E → C → F → D

3. Breadth First Search (BFS)

BFS is an algorithm for traversing or searching a tree or graph data structure. It starts at the tree root (or some arbitrary node of a graph, sometimes referred to as a 'search key') and explores the neighbor nodes at the present depth prior to moving on to the nodes at the next depth level.

Key Characteristics

  • Strategy: "Go wide, layer by layer."
  • Data Structure: Queue (FIFO - First-In, First-Out).
  • Use Cases: Finding the shortest path in unweighted graphs, peer-to-peer networks, crawler systems, broadcasting in networks.

Example Walkthrough (Starting at A, visiting neighbors alphabetically)

  1. Visit A. Add A to Queue. Queue: [A]. Visited: {A}.
  2. Dequeue A. Visit A's unvisited neighbors: B, C, D. Add them to Queue. Queue: [B, C, D]. Visited: {A, B, C, D}.
  3. Dequeue B. Visit B's unvisited neighbors: None (E is already visited via A implicitly in the traversal description, but let's be explicit: B's neighbors are A, E. A is visited. E is not visited). Wait, E is connected to B and C. If we visit neighbors of B after A, we visit E. Let's correct the trace.
  4. Dequeue B. Visit B's unvisited neighbor, E. Add E to Queue. Queue: [C, D, E]. Visited: {A, B, C, D, E}.
  5. Dequeue C. Visit C's unvisited neighbors: None (E is visited). Queue: [D, E].
  6. Dequeue D. Visit D's unvisited neighbors: None. Queue: [E].
  7. Dequeue E. Visit E's unvisited neighbors: F. Add F to Queue. Queue: [F]. Visited: {A, B, C, D, E, F}.
  8. Dequeue F. All reachable nodes visited.

BFS Traversal Output: A → B → C → D → E → F

4. C Implementation

Note: Graph is represented using an adjacency list with structures.

#include <stdio.h>
#include <stdlib.h>

// Maximum number of vertices
#define MAX_VERTICES 10

// Structure for a node in the adjacency list
struct Node {
    int vertex;
    struct Node next;
};

// Structure for the adjacency list
struct Graph {
    int numVertices;
    struct Node adjLists;
    int visited; // Array for DFS/BFS state
};

// Function to create a new node
struct Node createNode(int v) {
    struct Node newNode = (struct Node)malloc(sizeof(struct Node));
    newNode->vertex = v;
    newNode->next = NULL;
    return newNode;
}

// Function to create a graph
struct Graph createGraph(int vertices) {
    struct Graph graph = (struct Graph)malloc(sizeof(struct Graph));
    graph->numVertices = vertices;
    graph->adjLists = (struct Node)malloc(vertices  sizeof(struct Node));
    graph->visited = (int)malloc(vertices  sizeof(int));

    for (int i = 0; i < vertices; i++) {
        graph->adjLists[i] = NULL;
        graph->visited[i] = 0; // Not visited
    }
    return graph;
}

// Function to add an edge (undirected graph)
void addEdge(struct Graph graph, int src, int dest) {
    // Add edge from src to dest
    struct Node newNode = createNode(dest);
    newNode->next = graph->adjLists[src];
    graph->adjLists[src] = newNode;

    // Add edge from dest to src
    newNode = createNode(src);
    newNode->next = graph->adjLists[dest];
    graph->adjLists[dest] = newNode;
}

// Function for Depth First Search (Recursive)
void DFS(struct Graph graph, int vertex) {
    graph->visited[vertex] = 1;
    printf("%c ", vertex + 'A'); // Assuming vertices 0-5 are A-F

    struct Node adjList = graph->adjLists[vertex];
    struct Node temp = adjList;

    while (temp != NULL) {
        int connectedVertex = temp->vertex;
        if (graph->visited[connectedVertex] == 0) {
            DFS(graph, connectedVertex);
        }
        temp = temp->next;
    }
}

// Function for Breadth First Search
void BFS(struct Graph graph, int startVertex) {
    // Create a Queue for BFS
    int queue[MAX_VERTICES];
    int front = -1, rear = -1;

    graph->visited[startVertex] = 1;
    rear++;
    queue[rear] = startVertex;

    while (front != rear) {
        front++;
        int currentVertex = queue[front];
        printf("%c ", currentVertex + 'A');

        struct Node temp = graph->adjLists[currentVertex];

        while (temp) {
            int connectedVertex = temp->vertex;
            if (graph->visited[connectedVertex] == 0) {
                graph->visited[connectedVertex] = 1;
                rear++;
                queue[rear] = connectedVertex;
            }
            temp = temp->next;
        }
    }
}

// Helper to reset visited array
void resetVisited(struct Graph graph) {
    for (int i = 0; i < graph->numVertices; i++) {
        graph->visited[i] = 0;
    }
}

int main() {
    // Create graph for example (6 vertices: 0=A, ..., 5=F)
    struct Graph* graph = createGraph(6);
    // Edges from Fig 1: A-B, A-C, A-D, B-E, C-E, C-F
    addEdge(graph, 0, 1); // A-B
    addEdge(graph, 0, 2); // A-C
    addEdge(graph, 0, 3); // A-D
    addEdge(graph, 1, 4); // B-E
    addEdge(graph, 2, 4); // C-E
    addEdge(graph, 2, 5); // C-F

    printf("DFS Traversal (starting at A): ");
    DFS(graph, 0);
    printf("\n");

    resetVisited(graph);

    printf("BFS Traversal (starting at A): ");
    BFS(graph, 0);
    printf("\n");

    return 0;
}

Expected Output (C):

DFS Traversal (starting at A): A D C F B E 
BFS Traversal (starting at A): A D C B E F 

Note: The exact output sequence depends on the order of insertion in the adjacency list implementation. The trace above was slightly different due to neighbor order assumption, but the linear time algorithms are correct. The C output shows A-D-C-F-B-E for DFS, meaning it explored D, then C, then F, then backtracked to C, then to A, then to B, then to E. The BFS output shows A-D-C-B-E-F, meaning it visited layer 1 (D, C, B), then proceeded to visit their neighbors (E, F). Both cover all nodes.

5. Python Implementation

Note: Uses dictionary for adjacency list representation and Python's features.

class Graph:
    def __init__(self):
        self.adj_list = {}
        self.visited_dfs = set()
        self.visited_bfs = set()

    def add_edge(self, u, v, undirected=True):
        if u not in self.adj_list:
            self.adj_list[u] = []
        self.adj_list[u].append(v)
        if undirected:
            if v not in self.adj_list:
                self.adj_list[v] = []
            self.adj_list[v].append(u)

    def dfs_recursive(self, start_node, output=None):
        if output is None:
            output = []
            self.visited_dfs = set() # Reset for new call

        output.append(start_node)
        self.visited_dfs.add(start_node)

        # Ensure neighbors are sorted for deterministic output
        if start_node in self.adj_list:
            for neighbor in sorted(self.adj_list[start_node]):
                if neighbor not in self.visited_dfs:
                    self.dfs_recursive(neighbor, output)
        return output

    def bfs(self, start_node):
        queue = [start_node]
        visited = {start_node}
        output = []

        while queue:
            current_node = queue.pop(0)
            output.append(current_node)

            # Ensure neighbors are sorted for deterministic output
            if current_node in self.adj_list:
                for neighbor in sorted(self.adj_list[current_node]):
                    if neighbor not in visited:
                        visited.add(neighbor)
                        queue.append(neighbor)
        return output

if __name__ == "__main__":
    g = Graph()
    # Edges from Fig 1: A-B, A-C, A-D, B-E, C-E, C-F
    g.add_edge('A', 'B')
    g.add_edge('A', 'C')
    g.add_edge('A', 'D')
    g.add_edge('B', 'E')
    g.add_edge('C', 'E')
    g.add_edge('C', 'F')

    print("DFS Traversal (starting at A):", " -> ".join(g.dfs_recursive('A')))
    print("BFS Traversal (starting at A):", " -> ".join(g.bfs('A')))

Expected Output (Python):

DFS Traversal (starting at A): A -> B -> C -> E -> F -> D
BFS Traversal (starting at A): A -> B -> C -> D -> E -> F 

Note: The Python implementation sorts neighbors before traversal to ensure deterministic output, matching the initial example walkthrough closely. DFS visits A-B-E-C-F-D; BFS visits A-B-C-D-E-F.

Diagrams

depth-first-search-and-breadth-first-search - Diagram

depth-first-search-and-breadth-first-search - Diagram

Advertisement
Advertisement