Problem Statement
Given a graph with N
nodes and E
edges, check whether the graph is
bipartite or not.
A bipartite graph is a graph where for each edge (u, v)
, either u
belongs
to U and v
belong to V, or u
belongs to V or v
belongs
to U, where U and V are sets.
In other words, a graph is bipartite if it can be colored using only 2 colors, where the nodes’ colors are alternating.
Example illustrations can be found on Wikipedia
Note: A graph with odd cycles is cannot be bipartite.
General Idea | \(O(V+E)\)
Checking whether or not a graph is bipartite can be accomplished by attempting to color the graph using only 2 colors. If no color conflicts arise during this process, the graph is bipartite.
This algorithm can be implemeted using either DFS
or BFS
.
## Code
C++11 code below of a BFS
implementation
Variation
A common variation to this problem is, for example, given a city with V
intersections and E
streets, find the minimum numbers of communication towers
needed to cover the whole city, given that a communication tower can cover
the current intersection it is on and all the streets and intersections it is connected
to.
Wording plays a huge role when encountering this variation as we can, for example, replace communication tower with guard and the problem would still be valid and have the same solution.
General Idea of Variation
The general idea is the same as the original problem. However, this time around, we’ll keep track of the counts of both colors, where the colors in this case would represent the towers or guards of the problem.
At the end, we’ll take the minimum of both colors and we’ll end up with our answer.
Code
C++11 code below