#include <bits/stdc++.h>
using namespace std;
struct Graph
{
int V;
vector<list<int>> network;
Graph(int V);
void addEdge(int s, int v);
void performDFS(int s);
};
Graph::Graph(int V)
{
this->V = V;
network.resize(V);
}
void Graph::addEdge(int s, int v)
{
network[s].push_back(v);
}
void Graph::performDFS(int s)
{
vector<bool>visited;
visited.resize(V, false);
visited[s] = true;
list<int> Stack;
Stack.push_back(s);
cout<<s<<" ";
while(!Stack.empty())
{
int abc = Stack.back();
for(int adjacent:network[abc])
{
if(!visited[adjacent])
{
visited[adjacent] = true;
cout<<adjacent<<" ";
Stack.push_back(adjacent);
abc = adjacent;
}
}
Stack.pop_back();
}
}
int main()
{
Graph g(4);
g.addEdge(0, 1);
g.addEdge(0, 2);
g.addEdge(1, 2);
g.addEdge(2, 0);
g.addEdge(2, 3);
g.addEdge(3, 3);
g.performDFS(1);
}
The output should be 2 0 1 3, while this is giving 2 0 3 1.
- The traversal starts at 2, which is marked true and printed.
- Then adjacent is assigned 0, which is marked as explored, printed and pushed onto the stack. abc is changed to adjacent which is 0.
- After this, adjacent should get assigned 1, since it is the only unexplored edge around 0, but for some reason, it doesn't.
Need help with this...