0% found this document useful (0 votes)
21 views1 page

9 DFS

The document provides a C++ implementation of Depth First Search (DFS) for traversing a graph. It defines a DFS function that recursively visits nodes and prints them, starting from a specified node. The main function sets up a graph with 6 vertices, adds edges, and initiates the DFS traversal from node 0.

Uploaded by

dhanesh.mukkam
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
21 views1 page

9 DFS

The document provides a C++ implementation of Depth First Search (DFS) for traversing a graph. It defines a DFS function that recursively visits nodes and prints them, starting from a specified node. The main function sets up a graph with 6 vertices, adds edges, and initiates the DFS traversal from node 0.

Uploaded by

dhanesh.mukkam
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 1

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;
}

You might also like