I am confused why my code is producing wrong output.I am trying to do bfs for every node if it hasn't been visited yet, and trying to visit it's adj nodes too. Can anyone help me find the issue? here is my code:-
#include <bits/stdc++.h>
using namespace std;
int p = 1;
int ans[200005] = {-1};
bool bfs(vector<int> graph[], int x, int ans[])
{
queue<int> q;
q.push(x);
ans[x] = 1;
while (!q.empty())
{
int f = q.front();
q.pop();
for (auto it : graph[f])
{
if (ans[it] == -1)
ans[it] = 1 - ans[f], q.push(it);
else if (ans[it] == ans[f])
return true;
}
}
return false;
}
signed main()
{
int n, m;
cin >> n >> m;
vector<int> graph[n + 1];
for (int i = 1, a, b; i <= m; i++)
{
cin >> a >> b;
graph[a].push_back(b);
graph[b].push_back(a);
}
for (int i = 1; i <= n; i++)
{
if (ans[i] == -1)
{
if (bfs(graph, i, ans))
p = 0;
}
}
if (!p)
cout << "IMPOSSIBLE";
else
{
for (int i = 1; i <= n; i++)
{
cout << ans[i] + 1 << ' ';
}
}
}
input :-
5 3
1 2
1 3
4 5
expected output:-
1 2 2 1 2
received output:-
1 1 1 1 1