Detecting an Odd Cycle |
This algorithm checks whether an undirected graph contains an odd-length cycle by performing a BFS (Breadth-First Search) traversal from each unvisited vertex. It uses a coloring array to keep track of the vertices and their colors during the traversal. Initially, all vertices are uncolored (-1). When a vertex is visited, it is colored with either 0 or 1.
Time Complexity: O(m+n), where m is the number of edges and n is the number of vertices
bool oddCycle(vector<vector<in>> & graph) { vector <int> coloringArray; coloringArray.resize(graph.size(), -1); for (int j = 0; j <graph.size(); j++) { if (coloringArray[j] == -1) { coloringArray.at(j) = 1; queue <int> queue; queue.push(j); while (!queue.empty()) { int currentVertix = queue.front(); queue.pop(); if (graph.at(currentVertix).at(currentVertix) == 1) { return true; } for (int i = 0; i<graph.size(); i++) { if (graph.at(currentVertix).at(i)) { if (coloringArray[i] == -1) { coloringArray[i] = 1 - coloringArray[currentVertix]; queue.push(i); } else if (coloringArray[i] == coloringArray[currentVertix]) { return true; } } } } } } return false; }