• Breadth-First Search (BFS):

    • Explores neighbors level by level (breadth-wise).
    • Uses a queue.
    • Time complexity: \(O(V + E)\)
    • Applications: Shortest path in an unweighted graph.
    void BFS(int start, vector<vector<int>> &adj) {
        queue<int> q;
        vector<bool> visited(adj.size(), false);
        q.push(start);
        visited[start] = true;
    
        while (!q.empty()) {
            int node = q.front();
            q.pop();
    
            // Process node
            cout << node << " ";
    
            for (int neighbor : adj[node]) {
                if (!visited[neighbor]) {
                    q.push(neighbor);
                    visited[neighbor] = true;
                }
            }
        }
    }
    
    
  • Depth-First Search (DFS):

    • Explores as deep as possible along one branch before backtracking (depth-wise).
    • Uses a stack (or recursion).
    • Time complexity: \(O(V + E)\)
    • Applications: Cycle detection, pathfinding.
    void DFS(int node, vector<vector<int>> &adj, vector<bool> &visited) {
        visited[node] = true;
        cout << node << " "; // Process node
    
        for (int neighbor : adj[node]) {
            if (!visited[neighbor]) {
                DFS(neighbor, adj, visited);
            }
        }
    }