I am trying to learn graph theory and have been playing around with DFS. I want my code to search each node and detect any cycles in the graph.
#include <bits/stdc++.h>
using namespace std;
class Graph
{
public:
// each node has its own adjacency list
map<int, list<int>> adj;
// checking if each node has been visited or not
map<int, bool> visited;
void addEdge(int n1, int n2);
void DFS(int v, int w);
};
void Graph::addEdge(int n1, int n2)
{
// add each other to their own adjacency list
adj[n1].push_back(n2);
adj[n2].push_back(n1);
}
void Graph::DFS(int par, int cur)
{
// mark current node as visited
visited[cur] = true;
cout << cur << "\n";
// for each node adjacent
for (auto &i : adj[cur])
{
// if it has been visited and it is not the parent node (detects a cycle)
if (visited[i] && i != par)
{
cout << "Cycle detected! | ";
cout << "Adjacent node: " << i << " | ";
cout << "Parent node: " << par << "\n";
}
// run DFS from unvisited node
if (!visited[i])
{
DFS(cur, i);
}
}
}
int main()
{
// create graph
Graph graph;
graph.addEdge(0, 1);
graph.addEdge(1, 2);
graph.addEdge(1, 3);
graph.addEdge(2, 5);
graph.addEdge(2, 3);
graph.addEdge(3, 4);
graph.addEdge(4, 6);
// run DFS on the first node
graph.DFS(0, 0);
}
This is the graph I am trying to search:
However, when I run the code from the start node I get this output (the first number is the adjacent node that it sees and the second number is the current parent node):
0
1
2
5
3
Cycle detected! | Adjacent node: 1 | Parent node: 2
4
6
Cycle detected! | Adjacent node: 3 | Parent node: 0
For some reason, it detects one final cycle right before finishing the search. I haven't found any bugs or issues with my code and everyone I ask cannot find the problem. It would be great if someone could figure it out. Thanks for all the help!