ScholarQuill logoScholarQuillUniversity Notes
  • Notes
  • Past Papers
  • Blogs
  • Todo
Login
ScholarQuill logoScholarQuillUniversity Notes
Login
NotesPast PapersBlogsTodo
More
SubjectsDiscussionCGPA CalculatorGPA CalculatorStudent PortalCourse Outline
About
About usPrivacy PolicyReportContact
Notes
Past Papers
Blogs
Todo
Analytics
    Current Subject
    🧩
    Data Structures
    COMP2117
    Progress0 / 37 topics
    Topics
    1. Abstract Data Types2. Complexity Analysis3. Big Oh Notation4. Stacks (Linked Lists and Array Implementations)5. Recursion and analyzing recursive algorithms6. Divide and Conquer Algorithms7. Sorting Algorithms8. Selection Sort9. Insertion Sort10. Merge Sort11. Quick Sort12. Bubble Sort13. Heap Sort14. Shell Sort15. Radix Sort16. Bucket Sort17. Queue18. Dequeuer19. Priority Queues (linked and array implementations of queues)20. Linked List and Its Various Types21. Sorted Linked List22. Searching an Unsorted Array23. Binary Search for Sorted Arrays24. Hashing and Indexing25. Open Addressing and Chaining26. Trees and Tree Traversals27. Binary Search Trees28. Heaps29. M-Way Trees30. Balanced Trees31. Graphs32. Breadth-First Traversal33. Depth-First Traversal34. Topological Order35. Shortest Path36. Adjacency Matrix and Adjacency List Implementations37. Memory Management and Garbage Collection
    COMP2117›Depth-First Traversal
    Data StructuresTopic 33 of 37

    Depth-First Traversal

    4 minread
    752words
    Beginnerlevel

    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 load past papers

    Click on Show Past Papers to see past papers.
    On This Page
      Reading Stats
      Est. reading time4 min
      Word count752
      Code examples0
      DifficultyBeginner