M-Coloring Problem
Posted: 16 Dec, 2020
Difficulty: Moderate
You are given an undirected graph in the form of an adjacency matrix along with an integer M. You need to tell if you can color the vertices of the graph using at most M colors such that no two adjacent vertices are of the same color.
For example:
If the given adjacency matrix is:
[0 1 0]
[1 0 1]
[0 1 0] and M = 3.
The given adjacency matrix tells us that 1 is connected to 2 and 2 is connected to 3. So if we color vertex 1 with 2, vertex 2 with 1, and vertex 3 with 2, it is possible to color the given graph with 2 colors: M.
Input Format:
The first line of input contains a single integer T, representing the number of test cases or queries to be run.
Then the T test cases follow.
The first line of the test case contains two space-separated integers V and M, denoting the number of vertices in the undirected graph and the number of colors respectively.
Each of the next V lines contains V integers denoting the adjacency matrix of the undirected graph.
Output Format:
For each test case, you need to return “YES” if we can color the given graph with at most M colors. Otherwise, return “NO”. (without the inverted commas)
Note:
You are not required to print the expected output, it has already been taken care of. Just implement the function.
Constraints:
1 ≤ T ≤ 1000
1 ≤ V ≤ 20
1 ≤ M ≤ V
Time Limit : 1 sec
Approach 1
- We generate all possible combinations of colors possible for coloring the given graph.
- This can be done recursively by assigning a node each color from 1 to M and doing the same for all nodes.
- We further check if the adjacent vertices don’t have the same color.
- If we find such a combination of vertices, we return “YES”. Otherwise, we return “NO”.
Approach 2
- We generate all possible combinations of colors possible for coloring the given graph.
- An optimisation in this method would be that, we would assign the colors after checking if it is possible to make the vertex of that color. In the brute force method, we were checking this after assigning all the colors.
- We would assign each vertex a color from 1 to M, check if its adjacent vertex has a different color or not.
- Finally, if we get a configuration such that each node is colored from 1 to M and adjacent vertices are of different color, we return “YES”. Otherwise, we return “NO”.
SIMILAR PROBLEMS
Shortest Common Supersequence
Posted: 4 Mar, 2022
Difficulty: Hard
Mining Diamonds
Posted: 4 Mar, 2022
Difficulty: Hard
Minimum Number of Deletions and Insertions
Posted: 4 Mar, 2022
Difficulty: Moderate
Can You Print
Posted: 14 Apr, 2022
Difficulty: Easy
Prime Digit Sum
Posted: 17 Apr, 2022
Difficulty: Hard