0% found this document useful (0 votes)
8 views3 pages

DFS

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

DFS

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

//DFS

#include <iostream>
#include <stack>

const int MAX_NODES = 100;

void dfs(int graph[MAX_NODES][MAX_NODES], int start, int numNodes) {


bool visited[MAX_NODES] = {false};
std::stack<int> nodeStack;

nodeStack.push(start);
visited[start] = true;

while (!nodeStack.empty()) {
int currentNode = nodeStack.top();
nodeStack.pop();

std::cout << "Visited: " << currentNode << std::endl;


for (int i = 0; i < numNodes; i++) {
if (graph[currentNode][i] == 1 && !visited[i]) {
nodeStack.push(i);
visited[i] = true;
}
}
}
}

int main() {
int graph[MAX_NODES][MAX_NODES] = {0};
int numNodes, numEdges;

std::cout << "Enter number of nodes: ";


std::cin >> numNodes;

std::cout << "Enter number of edges: ";


std::cin >> numEdges;

std::cout << "Enter edges (start end): " << std::endl;


for (int i = 0; i < numEdges; i++) {
int start, end;
std::cin >> start >> end;
graph[start][end] = 1;
graph[end][start] = 1;
}

int startNode;
std::cout << "Enter the starXng node for DFS: ";
std::cin >> startNode;

std::cout << "DFS traversal starXng from node " << startNode << ":" << std::endl;
dfs(graph, startNode, numNodes);

return 0;
}

You might also like