0% found this document useful (0 votes)
6 views2 pages

Dfs

Uploaded by

jebalincy95
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)
6 views2 pages

Dfs

Uploaded by

jebalincy95
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/ 2

#include <iostream>

#include <vector>
#include <stack>

using namespace std;

class Graph {
private:
int V; // Number of vertices
vector<vector<int>> adj; // Adjacency list

public:
// Constructor to initialize the graph
Graph(int V) {
this->V = V;
adj.resize(V);
}

// Add an edge from vertex u to vertex v


void addEdge(int u, int v) {
adj[u].push_back(v);
adj[v].push_back(u); // For undirected graph
}

// DFS function to perform depth-first search


void DFS(int start) {
// Create a visited vector to mark visited vertices
vector<bool> visited(V, false);

// Create a stack for DFS


stack<int> s;

// Push the start vertex into the stack


s.push(start);

// Start DFS loop


while (!s.empty()) {
// Get the current vertex
int current = s.top();
s.pop();

// If the current vertex is not visited


if (!visited[current]) {
// Mark it as visited
visited[current] = true;
cout << current << " "; // Print the vertex (or take any
action you want)

// Push all adjacent vertices to the stack


for (int neighbor : adj[current]) {
if (!visited[neighbor]) {
s.push(neighbor);
}
}
}
}
}
};
int main() {
int vertices = 5;
Graph g(vertices);

// Adding edges
g.addEdge(0, 1);
g.addEdge(0, 2);
g.addEdge(1, 3);
g.addEdge(2, 4);

cout << "Depth First Search starting from vertex 0: ";


g.DFS(0); // Start DFS from vertex 0
cout << endl;

return 0;
}

You might also like