Depth First Searching
#include <iostream>
#include <vector>
using namespace std;
// Function to perform DFS
void DFS(int node, vector<int> adj[], vector<bool> &visited) {
// Mark the current node as visited
visited[node] = true;
cout << node << " "; // Print the current node
// Recursively visit all adjacent nodes (neighbors)
for (int neighbor : adj[node]) {
if (!visited[neighbor]) {
DFS(neighbor, adj, visited);
}
}
}
int main() {
// Number of nodes (vertices) and edges
int vertices = 6;
vector<int> adj[vertices]; // Adjacency list representation of the graph
// Adding edges to the graph
adj[0].push_back(1);
adj[0].push_back(2);
adj[1].push_back(3);
adj[1].push_back(4);
adj[2].push_back(5);
// To track visited nodes
vector<bool> visited(vertices, false);
// Perform DFS starting from node 0
cout << "DFS Traversal starting from node 0:" << endl;
DFS(0, adj, visited);
return 0;
}