ScholarQuill logoScholarQuillUniversity Notes
My Semester
Explore Notes
Past Papers12 New
Video CoursesNew
Search
Settings
Study Tools
GPA/CGPA Calculator
Schedule & To-Do
Student Portal
Contact
Contact
ScholarQuill logo
My Semester
Explore Notes
Past Papers12 New
Video CoursesNew
Search
Settings
GPA/CGPA Calculator
Schedule & To-Do
Student Portal
Contact
ScholarQuill logoScholarQuillUniversity Notes
Study PortalCOMP2117Depth First Traversal
Ctrl + K
Login
Explore
Search
Semester
Papers
CGPA
    COMP2117

    Data Structures

    Progress0 / 37 done
    Topics37
    1Abstract Data Types2Complexity Analysis3Big Oh Notation4Stacks (Linked Lists and Array Implementations)5Recursion and analyzing recursive algorithms6Divide and Conquer Algorithms7Sorting Algorithms8Selection Sort9Insertion Sort10Merge Sort11Quick Sort12Bubble Sort13Heap Sort14Shell Sort15Radix Sort16Bucket Sort17Queue18Dequeuer19Priority Queues (linked and array implementations of queues)20Linked List and Its Various Types21Sorted Linked List22Searching an Unsorted Array23Binary Search for Sorted Arrays24Hashing and Indexing25Open Addressing and Chaining26Trees and Tree Traversals27Binary Search Trees28Heaps29M-Way Trees30Balanced Trees31Graphs32Breadth-First Traversal33Depth-First Traversal34Topological Order35Shortest Path36Adjacency Matrix and Adjacency List Implementations37Memory Management and Garbage Collection
    4 min read
    Topic 33 of 37
    Topic Study Note Illustration
    33

    Depth-First Traversal

    Depth-First Search (DFS) is an algorithm for traversing or searching through tree or graph data structures. It explores as far down a branch as possible before backtracking....

    Depth-First Traversal (DFS)

    Depth-First Search (DFS) is an algorithm for traversing or searching through tree or graph data structures. It explores as far down a branch as possible before backtracking. This method can be implemented using recursion or a stack.

    Key Characteristics

    1. Exploration: DFS goes deep into a branch of the graph before exploring other branches, making it useful for scenarios where you want to explore all possibilities.
    2. Stack Data Structure: DFS can be implemented using a stack (either explicitly or via recursion).
    3. Path Finding: DFS can be used to find paths in a graph and to explore all possible configurations or states.

    Algorithm Steps

    1. Initialize:

      • Start from a selected node (root for trees).
      • Maintain a stack to track the nodes that need to be explored.
      • Keep a list (or array) to track visited nodes.
    2. Process the Stack:

      • While the stack is not empty:
        • Pop the top node from the stack.
        • Process (or visit) the node (e.g., print its value).
        • Push all unvisited adjacent nodes onto the stack.
    3. Repeat until all nodes are visited.

    DFS Implementation

    Here’s an implementation of DFS using an adjacency list representation of a graph in C++:

    #include <iostream>
    #include <vector>
    #include <stack>
    using namespace std;
    
    class Graph {
    private:
        int V; // Number of vertices
        vector<vector<int>> adj; // Adjacency list
    
    public:
        Graph(int v) : V(v), adj(v) {}
    
        void addEdge(int u, int v) {
            adj[u].push_back(v); // Add edge from u to v
            // If undirected, uncomment the next line:
            // adj[v].push_back(u); // Add edge from v to u
        }
    
        void DFS(int start) {
            vector<bool> visited(V, false); // Track visited vertices
            stack<int> s; // Stack for DFS
    
            s.push(start); // Push the start node onto the stack
    
            while (!s.empty()) {
                int node = s.top(); // Get the top node
                s.pop(); // Remove the top node
    
                if (!visited[node]) {
                    visited[node] = true; // Mark the node as visited
                    cout << node << " "; // Process the node
    
                    // Push all adjacent unvisited nodes onto the stack
                    for (int i = adj[node].size() - 1; i >= 0; --i) {
                        if (!visited[adj[node][i]]) {
                            s.push(adj[node][i]);
                        }
                    }
                }
            }
            cout << endl; // New line after traversal
        }
    };
    
    int main() {
        Graph g(5); // Create a graph with 5 vertices
        g.addEdge(0, 1);
        g.addEdge(0, 4);
        g.addEdge(1, 2);
        g.addEdge(1, 3);
        g.addEdge(1, 4);
        g.addEdge(2, 3);
        g.addEdge(3, 4);
    
        cout << "DFS Traversal starting from vertex 0: ";
        g.DFS(0); // Start DFS from vertex 0
    
        return 0;
    }
    

    Explanation of the Code

    1. Graph Class:

      • Contains the number of vertices and an adjacency list to represent edges.
      • addEdge Function: Adds an edge from vertex uuu to vertex vvv. If the graph is undirected, you would typically add the reverse edge as well.
    2. DFS Function:

      • Initializes a visited vector and a stack.
      • Pushes the starting vertex onto the stack.
      • Processes nodes in the stack, marking and pushing their unvisited neighbors.
    3. Main Function:

      • Creates a graph, adds edges, and calls the DFS function to traverse from a starting vertex.

    Complexity Analysis

    • Time Complexity: O(V+E)O(V + E)O(V+E)

      • VVV is the number of vertices, and EEE is the number of edges. Each vertex and edge is processed once.
    • Space Complexity: O(V)O(V)O(V)

      • For the visited list and the stack.

    Applications of DFS

    1. Path Finding: Finding paths between nodes in a maze or network.
    2. Topological Sorting: Ordering of vertices in a directed acyclic graph (DAG).
    3. Cycle Detection: Checking for cycles in graphs.
    4. Connected Components: Identifying connected components in undirected graphs.

    Conclusion

    Depth-First Search is a versatile traversal algorithm that systematically explores branches of a graph. Its use of a stack allows for deep exploration, making it suitable for a variety of applications in graph theory, pathfinding, and solving problems that involve backtracking. Understanding DFS is essential for solving complex problems in computational fields.

    ← Previous topic 32
    Breadth-First Traversal
    Next topic 34 →
    Topological Order

    Past Papers

    Open this section to view and download past papers

    Click on Show Past Papers to load available exam papers.

    Reading Progress
    0%
    4mremaining
    752words
    Beginnerlevel
    On This Page

    No headings found

    Study Toolkit

    Subject Portal

    Data Structures