AlgoFrames

Return the 2-coloring

Standard · Write code · about 12 min

Return an array colors of length n with every value 0 or 1, so that every edge joins nodes of different colors. In each connected part, the lowest-numbered node gets color 0. If no such coloring exists, return []. In JavaScript, buildAdjacency(graph) returns the adjacency lists.

Example 1

Input:

[{"n":5,"edges":[[0,1],[1,2],[3,4]],"directed":false}]

Output:

[0,1,0,0,1]

Nodes 0 and 3 start their parts with color 0.

Example 2

Input:

[{"n":3,"edges":[[0,1],[1,2],[2,0]],"directed":false}]

Output:

[]

A triangle has an odd cycle.

Constraints

  • 1 ≤ n ≤ 200 nodes, numbered 0 to n - 1
  • At most 3n edges; repeated edges and self-loops may appear
  • The graph is undirected and may be disconnected

Learn the idea first: Bipartite check by 2-coloring, a visual lesson.

More Bipartite check by 2-coloring problems