Thursday, February 19, 2015

Checking if a given graph is Bipartite (BFS) JAVA

Algorithm:

1. Use a queue q.2. Add any node to q.3. For all those nodes that are connected to the current node polled from q, check if they have been assigned a color, if they have a color and it is the same as the current node, the graph is not bipartite and we need to stop the procedure else if they don't have any color add them to queue also (only if they have not been added previously [ use a boolean array or a HashSet for checking this ] ).4. If the queue q is empty in the end it means that the given graph is bipartite.

Note: In case the graph is disjoint, we need to add all the given nodes to the queue and then check for all components connected to the current node popped from the queue.