Is Graph Bipartite?
Problem
There is an undirected graph with n
nodes, where each node is numbered between 0
and n - 1
. You are given a 2D array graph
, where graph[u]
is an array of nodes that node u
is adjacent to. More formally, for each v
in graph[u]
, there is an undirected edge between node u
and node v
. The graph has the following properties:
- There are no self-edges (
graph[u]
does not containu
). - There are no parallel edges (
graph[u]
does not contain duplicate values). - If
v
is ingraph[u]
, thenu
is ingraph[v]
(the graph is undirected). - The graph may not be connected, meaning there may be two nodes
u
andv
such that there is no path between them.
A graph is bipartite if the nodes can be partitioned into two independent sets A
and B
such that every edge in the graph connects a node in set A
and a node in set B
.
Return true
if and only if it is bipartite.
Solution Approach
Expected Time complexity:
Click - to see solution code
- C++
class Solution {
public:
bool dfs_helper(vector<vector<int>> Graph, vector<int>& visited, int par,
int node, int color) {
visited[node] = color; // painted
for (auto nbr : Graph[node]) { // traversing nbrs
if (nbr != par and visited[nbr] == 0) {
bool value = dfs_helper(Graph, visited, node, nbr, 3 - color);
if (value == false) return false;
} else if (visited[nbr] == color)
return false;
}
return true;
}
bool dfs(vector<vector<int>> Graph, int N) {
vector<int> visited(N + 1);
int color = 1;
for (int i = 0; i < N; i++) {
if (visited[i] == 0) {
bool ans = dfs_helper(Graph, visited, -1, i, 1);
if (ans == false) return ans;
}
}
return true;
}
bool isBipartite(vector<vector<int>>& graph) {
int n = graph.size();
return dfs(graph, n);
}
};