Bipartite-graph
Problem Statement:
Given an adjacency list / matrix representing a graph with V vertices indexed from 0, the task is to determine whether the graph is bipartite or not. You can use queue data structure to check the graph.
Video Explanation

Definition:
A bipartite graph is a type of graph where the set of vertices can be divided into two distinct sets such that no two vertices within the same set are adjacent. In other words, if you were to color the graph using two colors, it would be possible to color it in such a way that no two connected vertices have the same color. This property makes bipartite graphs useful in various applications, including matching problems, scheduling, and network flow analysis, as they can represent relationships where entities can be classified into two categories.
Approach
The approach to check if a graph is bipartite involves using BFS or DFS to color the graph with two colors, ensuring that no two adjacent vertices share the same color.
Algorithm Steps to Check if a Graph is Bipartite:
-
Initialize Colors: Create an array
colorof size V (number of vertices) and initialize all elements to -1, indicating that no vertices have been colored. -
BFS for Each Component: For each vertex
startfrom 0 to V-1:- If
color[start]is not -1, continue to the next vertex (this vertex is already colored).
- If
-
Start BFS:
- Initialize a queue and push the
startvertex into it. - Color
startwith color 0.
- Initialize a queue and push the
-
Process the Queue:
- While the queue is not empty, dequeue a vertex and check its neighbors:
- Color uncolored neighbors with the opposite color.
- If a neighbor has the same color as the current vertex, return false (the graph is not bipartite).
- While the queue is not empty, dequeue a vertex and check its neighbors:
-
Completion: If all vertices are processed without conflicts, return true (the graph is bipartite).
Time Complexity:
- The bipartite graph checking algorithm has a time complexity of
O(V^2)with an adjacency matrix, whereVis the number of vertices. If an adjacency list is used, the complexity isO(V + E), withEbeing the number of edges.