Is this bibartite detection algorithm correct?

44 Views Asked by At

I have developed an algorithm to determine whether an undirected graph is bipartite or not.

Starting at a random node we mark that node as 1, then we mark all it;s neighbours to be group 2 and push all of them to a stack.

While the stack is not empty, we pop from it an element.

We travel to each neighbour of this element.

If the element has not been marked, we marke it to be the opposite goup from the current node (if the current node is group 1 we mark it group 2 and vice versa). Then we push that element to the stack

If the element has been marked and it is the same group as the current node we terminate and say the graph is not bipartite.

If the stack is empty we say the graph is bipartite.

I tried to generate a proof of correctness and think it is correct but I am not really sure.

I have a C++ code I made for it to test it, if that makes things clearer for people:

int flip_group(int i) {
    if(i==1) return 2;
    return 1;
}
bool isBipartite(vector<vector<int>>& graph) {
    if(graph.size() == 0) return true;

    vector<int> group_list(graph.size(), 0);
    vector<int> stack;
    stack.push_back(0);
    group_list[0] = 1;

    while(stack.size() > 0) {
        int c_node = stack[stack.size()-1];
        stack.pop_back();

        for(int n_node: graph[c_node]) {
            if(group_list[n_node] == 0) {
                group_list[n_node] = flip_group(group_list[c_node]);
                stack.push_back(n_node);
            }
            else if(group_list[n_node] == group_list[c_node])
                return false;
        }
    }
    return true;
}