Question

Lets say I have a graph G with its adjacency matrix A. I know that G is bipartite. How can I split the vertices in G into the two sets that always form a bipartite graph? Thanks!

Was it helpful?

Solution

Declare an array which of size equal to the number of vertices, setting each element to 0 initially. Then perform a depth-first search through the graph, recording the "level number" that you are on as you go. This starts at 1, and alternates between 1 and 2 with each edge traversed. For every vertex reached, assign the current level to the corresponding entry of which, and (if it was previously 0) recurse to process its children. Afterwards, all elements of which will be either 1 or 2, and which[i] indicates which set vertex i belongs to.

Intuitively, you can imagine that each traversal from parent to child in the DFS takes you "down" a level, and each traversal back takes you back "up". By the bipartite property, all vertices on even levels can be connected only to vertices on odd levels and vice versa, so labelling nodes "even" or "odd" suffices to partition them into the two sets.

If your graph contains more than one component, you will of course need a separate DFS for each component.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top