Search code examples
graphbreadth-first-searchbipartite

Can anyone spot what is wrong with that code?


I have been trying to solve a problem from coursera.

Problem description: Given an undirected graph with 𝑛 vertices and 𝑚 edges, check whether it is bipartite.

Input Format. A graph is given in the standard format.

Constraints. 1 ≤ 𝑛 ≤ 105, 0 ≤ 𝑚 ≤ 105. Output Format. Output 1 if the graph is bipartite and 0 otherwise.

Input:
4 4
1 2
4 1
2 3
3 1
Output:
0
Input:
5 4
5 2
4 2
3 4
1 4
Output:
1

I came up with a solution in c++ that looks like

#include <bits/stdc++.h>
using namespace std;
#define vvi vector<vector<int>>
#define vi vector<int>
#define qi queue<int>
int bfs(vvi adj, int s, vi &disc, vi &dist)
{
    disc[s] = 1; dist[s] = 0;
    qi q;
    q.push(s);
    while(!q.empty())
    {
        int u = q.front(); q.pop();
        for(int i: adj[u])
        {
            if(!disc[i])
            {
                disc[i] = 1;
                q.push(i);
                dist[i] = dist[u]+1;
            }else if(dist[u]==dist[i])
            {
                return 0;
            }
        }
    }
    return 1;
}
bool isBipartite(vvi adj, vi &disc, vi &dist)
{
    for(int i=0;i<adj.size();++i)
    {
        if(!disc[i])
        {
            if(!bfs(adj, i, disc, dist))
            {
                return 0;
            }
        }
    }
    return 1;
}
int main()
{
    int n, m;
    cin >> n >> m;
    vvi adj(n);
    for(int i=0;i<m;++i)
    {
        int x, y;
        cin >> x >> y;
        adj[x-1].push_back(y-1);
        adj[y-1].push_back(x-1);
    }
    vi dist(n);
    vi disc(n, 0);
    cout << isBipartite(adj, disc, dist);
 
}

But this solution is generating wrong answer on test case 3. Can anyone figure out what I have missed in that code? Thanks in advance. ♥


Solution

  • Your logic seems flawless, there is a possible cause of error: you don't pass adj parameter as a reference. This mean that for every call of bfs method the graph will be copied. If 3rd test case is an isolated graph (no edges) that would be bad. Sometimes runtime error and memory exceeded error are treated by the online judge as a non existent wrong answer.