Is Graph Bipartition
Given an undirected graph
, returntrue
if and only if it is bipartite.
Recall that a graph is_bipartite_if we can split it's set of nodes into two independent subsets A and B such that every edge in the graph has one node in A and another node in B.
The graph is given in the following form:graph[i]
is a list of indexesj
for which the edge between nodesi
andj
exists. Each node is an integer between0
andgraph.length - 1
. There are no self edges or parallel edges:graph[i]
does not containi
, and it doesn't contain any element twice.
Example
Note
Assign RED color to the source vertex (putting into set U).
Color all the neighbors with BLUE color (putting into set V).
Color all neighbor’s neighbor with RED color (putting into set U).
This way, assign color to all vertices such that it satisfies all the constraints of m way coloring problem where m = 2.
While assigning colors, if we find a neighbor which is colored with same color as current vertex, then the graph cannot be colored with 2 vertices (or graph is not Bipartite)
Code
Last updated