I am trying to solve the question, detect cycle in a undirected graph. I have understood the logic and implemented it but my code is not giving the correct output. It is printing true in every case. I am not able to find what mistake i am doing.
Below is my C++ Code:
#include <iostream>
#include <queue>
#include <vector>
using namespace std;
int main()
{
int n, m;
cin >> n >> m;
vector<int> arr[n + 1];
for (int i = 0; i < m; i++)
{
int u, v;
cin >> u >> v;
arr[u].push_back(v);
arr[v].push_back(u);
}
bool flag = false;
vector<int> visited(n + 1, 0);
for (int i = 1; i < n + 1; i++)
{
if (visited[i] != 1)
{
queue<pair<int, int>> q;
q.push({i, -1});
visited[i] = 1;
while (!q.empty())
{
int node = q.front().first;
int pre = q.front().second;
q.pop();
for (int j = 0; j < arr[node].size(); j++)
{
if (!visited[j])
{
visited[j] = 1;
q.push({j, node});
}
else if (j != pre)
flag = true;
}
}
}
}
if (flag)
cout << "True";
else
cout << "false";
}
Please Help I am stuck on it from 3 days.