Recursion and Backtracking Searching with constraints
334. M-Coloring
You are given an undirected graph with n vertices, numbered from 0 to n - 1. Each row [a, b] of
edges is an edge between vertices a and b. You are also given an integer m.
We want to give every vertex one of m colors so that the two ends of every edge get different colors.
Return true if this can be done, and false if it cannot.
You do not have to use all m colors. An edge always joins two different vertices, and no two edges join
the same pair of vertices.
Example 1
Input: n = 5
edges = [[0, 1],
[1, 2],
[2, 3],
[3, 4],
[4, 0]]
m = 3
trueExplanation: The edges form a ring of five vertices. Two colors would have to alternate around it, and with five vertices, 4 and 0 would end up the same. A third color fixes that: vertices 0 to 4 can take colors 1, 2, 1, 2 and 3.
Example 2
Input: n = 6
edges = [[0, 1],
[1, 2],
[3, 4],
[4, 5],
[5, 3]]
m = 2
falseExplanation: Vertices 0, 1 and 2 can alternate two colors. But vertices 3, 4 and 5 are all joined to each other, so
they need three different colors. Every vertex must get a color, so the answer is false.
Example 3
Input: n = 3, edges = [], m = 1
trueExplanation: With no edges, nothing can clash, so one color is enough for all three vertices.
Check your understanding
Work out the answer for this input before you write any code.
Constraints
1 ≤ n ≤ 100 ≤ edges.length ≤ n · (n − 1) / 2edges[i].length == 20 ≤ ai, bi < nandai ≠ bi- No two edges join the same pair of vertices.
1 ≤ m ≤ n
Clarifying questions
What you would ask an interviewer before writing any code.