0

I was doing a problem on SPOJ SPOJ:BUGLIFE It required me to check whether the graph was bipartite or not. I know the method for a single connected graph, but for a combination of disconnected graphs, my method gives Time limit exceeded error. Here's my approach - Breadth First Search, using Circular Queues with the graph implemented by adjacency lists. method -> Choose a source, and if that source vertex=unvisited, then start a Breadth First Search assuming it to be the source. If I found a conflict in the BFS, then I abort the whole thing. Else I move to another un-visited source. How can I make this faster? or better?

P.S. I am new to Graph Theory, so please explain in detail.

  • I don't know what is Time limit error but If you know how to check bipartiteness for a connected graph then you should check bipartiteness for all connected sub-graphs and if all tests pass then your graph is bipartite. – a.lasram Jun 24 '13 at 22:13
  • Time limit error means that the program takes more time to execute with the given input (which is quite large) than is allowed. – user1733947 Jun 25 '13 at 09:14

1 Answers1

0

The following implementation (C++ version) is fast enough when testing in very large dataset (edages>1000). Hope it helps.

struct NODE
{
    int color;
    vector<int> neigh_list;
};

bool checkAllNodesVisited(NODE *graph, int numNodes, int & index);

bool checkBigraph(NODE * graph, int numNodes)
{
    int start = 0;

    do 
    {
        queue<int> Myqueue;
        Myqueue.push(start);
        graph[start].color = 0;

        while(!Myqueue.empty())
        {
            int gid = Myqueue.front();
            for(int i=0; i<graph[gid].neigh_list.size(); i++)
            {
                int neighid = graph[gid].neigh_list[i];
                if(graph[neighid].color == -1)
                {
                    graph[neighid].color = (graph[gid].color+1)%2; // assign to another group
                    Myqueue.push(neighid);
                }
                else
                {
                    if(graph[neighid].color == graph[gid].color) // touble pair in the same group
                        return false;
                }
            }
            Myqueue.pop();
        }
    } while (!checkAllNodesVisited(graph, numNodes, start)); // make sure all nodes visited 
                                            // to be able to handle several separated graphs, IMPORTANT!!!

    return true;
}

bool checkAllNodesVisited(NODE *graph, int numNodes, int & index)
{
    for (int i=0; i<numNodes; i++)
    {
        if (graph[i].color == -1)
        {
            index = i;
            return false;
        }
    }

    return true;
}
herohuyongtao
  • 49,413
  • 29
  • 133
  • 174