#include<bits/stdc++.h>
using namespace std;
// Function to add an edge to the adjacency list
void addEdge(vector<int> adj[], int u, int v) {
adj[u].push_back(v); // Add v to u's list
adj[v].push_back(u); // Add u to v's list (for undirected graph)
}
// Function to perform DFS using a stack
void DFS(vector<int> adj[], int V, int start) {
vector<bool> visited(V, false); // To keep track of visited nodes
stack<int> st; // Stack for DFS
st.push(start); // Push the starting node to the stack
cout << "DFS traversal starting from node " << start << ": ";
while (!st.empty()) {
int node = st.top(); // Get the top element
st.pop();
// If the node is not visited, process it
if (!visited[node]) {
cout << node << " ";
visited[node] = true;
}
// Push all unvisited neighbors to the stack
for (int neighbor : adj[node]) {
if (!visited[neighbor]) {
st.push(neighbor);
}
}
}
cout << endl;
}
int main() {
int V = 12; // Number of vertices
vector<int> adj[V]; // Adjacency list
// Adding edges
addEdge(adj, 0, 1);
addEdge(adj, 0, 4);
addEdge(adj, 0, 2);
addEdge(adj, 1, 4);
addEdge(adj, 2, 4);
addEdge(adj, 2, 9);
addEdge(adj, 2, 5);
addEdge(adj, 2, 10);
addEdge(adj, 9, 11);
addEdge(adj, 10, 11);
addEdge(adj, 5, 6);
addEdge(adj, 5, 7);
addEdge(adj, 5, 8);
addEdge(adj, 7, 8);
// Perform DFS starting from node 0
DFS(adj, V, 0);
return 0;
}
I2luY2x1ZGU8Yml0cy9zdGRjKysuaD4KdXNpbmcgbmFtZXNwYWNlIHN0ZDsKCi8vIEZ1bmN0aW9uIHRvIGFkZCBhbiBlZGdlIHRvIHRoZSBhZGphY2VuY3kgbGlzdAp2b2lkIGFkZEVkZ2UodmVjdG9yPGludD4gYWRqW10sIGludCB1LCBpbnQgdikgewogICAgYWRqW3VdLnB1c2hfYmFjayh2KTsgLy8gQWRkIHYgdG8gdSdzIGxpc3QKICAgIGFkalt2XS5wdXNoX2JhY2sodSk7IC8vIEFkZCB1IHRvIHYncyBsaXN0IChmb3IgdW5kaXJlY3RlZCBncmFwaCkKfQoKLy8gRnVuY3Rpb24gdG8gcGVyZm9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