0

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.

WhozCraig
  • 65,258
  • 11
  • 75
  • 141
  • 2
    Your code is entirely iterative. It should be fairly straightforward to run in a *debugger*, step line by line with a known-input/known-answer test, and find where things went off the rails. So.. what happened when you tried that ? – WhozCraig Feb 07 '22 at 18:10
  • Can you post the link for the question if there is one? You print 'True' but you print 'false' with lowercase f. If it's validated by computers, it may fail. And your solution doesn't work if the graph has loops or multiple edges. – ParSal Feb 07 '22 at 18:24
  • 1
    Contrary to the above comment, **Don't post links.** They rot and get blocked for a number of different reasons. If the information at the link is necessary to understanding the question, the question becomes not useful. Instead of linking, summarize the important information from the link in the question. – user4581301 Feb 07 '22 at 18:30
  • @WhozCraig I don't know how to use debugger – ABHIRAJ RAM Feb 08 '22 at 08:15
  • No time like the present. And btw, `vector arr[n + 1];` is a recipe or disaster. variable length arrays are non-standard in C++, and are an even *worse* idea with non-POD. I'd switch that to `std::vector> arr(n+1);` – WhozCraig Feb 08 '22 at 09:42

0 Answers0