Given a connected graph, check if the graph is bipartite or not. A bipartite graph is possible if the graph coloring is possible using two colors such that vertices in a set are colored with the same color. Note that it is possible to color a cycle graph with even cycle using two colors. For example, see the following graph.
It is not possible to color a cycle graph with an odd cycle using two colors.
- Use a color array which stores 0 or 1 for every node which denotes opposite colors.
- Call the function DFS from any node.
- If the node u has not been visited previously, then assign !color[v] to color[u] and call DFS again to visit nodes connected to u.
- If at any point, color[u] is equal to !color[v], then the node is bipartite.
- Modify the DFS function such that it returns a boolean value at the end.
Below is the implementation of the above approach:
Graph is Bipartite
Time Complexity: O(N)
Auxiliary Space: O(N)
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
- Check whether a given graph is Bipartite or not
- Maximum number of edges to be added to a tree so that it stays a Bipartite graph
- Maximum number of edges in Bipartite graph
- Check if a graph is strongly connected | Set 1 (Kosaraju using DFS)
- Check if the given permutation is a valid DFS of graph
- Transitive Closure of a Graph using DFS
- Graph implementation using STL for competitive programming | Set 1 (DFS of Unweighted and Undirected)
- Minimum number of edges between two vertices of a graph using DFS
- Maximum Bipartite Matching
- Minimum Bipartite Groups
- Depth First Search or DFS for a Graph
- DFS for a n-ary tree (acyclic graph) represented as adjacency list
- Tree, Back, Edge and Cross Edges in DFS of Graph
- Printing pre and post visited times in DFS of a graph
- Print the lexicographically smallest DFS of the graph starting from 1
- Calculate number of nodes between two vertices in an acyclic Graph by DFS method
- Count the number of nodes at a given level in a tree using DFS
- Find the number of islands | Set 1 (Using DFS)
- Calculate number of nodes in all subtrees | Using DFS
- Diameter of a tree using DFS
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.
Improved By : RishiAgrawal