Any hints to how can you determine if an undirected graph can be colored with only 2 colors? How could that be implemented in java?
-
1Any constraints? just color n/2 nodes with color 1 and n/2 nodes with color 2 =) – Enrique Nov 29 '10 at 00:39
-
1I found similar question which might help you, http://stackoverflow.com/questions/1838934/checking-for-odd-cycles-in-an-undirected-graph – Eternal Noob Nov 29 '10 at 00:42
-
what confuses me is the fact that we are suppose to prove whether is possible or not to color an undirected graph using 2 colors. – Nov 29 '10 at 00:43
-
1Find a cycle with an odd number of nodes. The rest is left as an exercise. :-) – Laurence Gonsalves Nov 29 '10 at 00:45
-
Hint: think about what properties an undirected graph that can't be colored would have to have – matt b Nov 29 '10 at 01:45
2 Answers
Do a breadth-first search on the graph. At every even depth, color the nodes one color, say red, and at the odd-depths, you color the nodes blue. Every time you have a non-tree edge (an edge between two nodes you have already visited) verify that the colors are different. If the graph has several connected components, you just repeat the search on each component.

- 21,379
- 8
- 78
- 117
That is same as determining if the graph is bipartite. To do that, you have to check if any odd-length cycle exists in the graph. For that, you do a breadth-first search on the graph. If at any level in the BFS, there is any edge between the nodes of the same level, then the graph is not bipartite, i.e., it can't be colored using only 2 colors. (Assuming the constraint is that the adjacent nodes should be of different colors)

- 794
- 8
- 23