![]() |
VOOZH | about |
Given a weighted and undirected graph, we need to find if a cycle exist in this graph such that the sum of weights of all the edges in that cycle comes out to be odd.
Examples:
Input : Number of vertices, n = 4, Number of edges, m = 4 Weighted Edges = 1 2 12 2 3 1 4 3 1 4 1 20 Output : No! There is no odd weight cycle in the given graph
Input : Number of vertices, n = 5, Number of edges, m = 3 Weighted Edges = 1 2 1 3 2 1 3 1 1 Output : Yes! There is an odd weight cycle in the given graph
The solution is based on the fact that "If a graph has no odd length cycle then it must be Bipartite, i.e., it can be colored with two colors"
The idea is to convert given problem to a simpler problem where we have to just check if there is cycle of odd length or not. To convert, we do following
Let's make an another graph for graph shown above (in example 1)
👁 cycle odd weight undirected graph
Here, edges [1 --- 2] have be broken in two parts such that [1-pseudo1-2] a pseudo node has been introduced. We are doing this so that each of our even weighted edge is taken into consideration twice while the edge with odd weight is counted only once. Doing this would help us further when we color our cycle. We assign all the edges with weight 1 and then by using 2 color method traverse the whole graph.
Now we start coloring our modified graph using two colors only. In a cycle with even number of nodes, when we color it using two colors only, none of the two adjacent edges have the same color. While if we try coloring a cycle having odd number of edges, surely a situation arises where two adjacent edges have the same color. This is our pick! Thus, if we are able to color the modified graph completely using 2 colors only in a way no two adjacent edges get the same color assigned to them then there must be either no cycle in the graph or a cycle with even number of nodes. If any conflict arises while coloring a cycle with 2 colors only, then we have an odd cycle in our graph.
Implementation:
No
Time Complexity: O(N*N), as we are using a loop to traverse N times and in each traversal we are calling the function twoColorUtil which costs O(N) time.
Auxiliary Space: O(N), as we are using extra space.