oneby7

Recursion and Backtracking Searching with constraints

334. M-Coloring

Hard

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

01234

Input: n = 5 edges = [[0, 1], [1, 2], [2, 3], [3, 4], [4, 0]] m = 3

Output: true

Explanation: 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

012345

Input: n = 6 edges = [[0, 1], [1, 2], [3, 4], [4, 5], [5, 3]] m = 2

Output: false

Explanation: 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

012

Input: n = 3, edges = [], m = 1

Output: true

Explanation: 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.

n = 6 edges = [[0, 1], [0, 2], [0, 3], [0, 4], [0, 5]] m = 2

Constraints

  • 1 ≤ n ≤ 10
  • 0 ≤ edges.length ≤ n · (n − 1) / 2
  • edges[i].length == 2
  • 0 ≤ ai, bi < n and ai ≠ 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.

Hints

Interview follow-ups

Runs in your browser
Code
Runs in your browser for now · some things may not work as expectedLn 1, Col 1

Article

Send feedback

Thank you for helping. We read every report and fix what is wrong.

How do you feel about oneby7?

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.