Skip to content

Implemented M Coloring Problem #1562

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
65 changes: 65 additions & 0 deletions Backtracking/MColoringProblem.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
/*
Problem: M Coloring Problem
Given a graph represented as an adjacency matrix and a number M (number of colors),
determine if the graph can be colored with up to M colors such that no two adjacent
vertices share the same color.

What is the M Coloring Problem?
- This problem is about coloring a graph's vertices with at most M different colors
such that no two adjacent vertices have the same color.

Example:
- Consider a triangle (3 nodes connected cyclically). We'd need 3 colors to color each vertex
without adjacent vertices having the same color.

Solution:
- We will be using backtracking to solve this question.
- Color a vertex, then move to an adjacent vertex and try all colors. If a color is valid,
continue to the next vertex, else backtrack.
*/

class MColoring {
constructor(graph, m) {
this.graph = graph; // adjacency matrix representation
this.m = m;
this.colors = new Array(graph.length).fill(0);
}

isSafe(vertex, color) {
for (let i = 0; i < this.graph.length; i++) {
if (this.graph[vertex][i] && this.colors[i] === color) {
return false;
}
}
return true;
}

solveColoring(vertex = 0) {
if (vertex === this.graph.length) {
return true;
}

for (let color = 1; color <= this.m; color++) {
if (this.isSafe(vertex, color)) {
this.colors[vertex] = color;

if (this.solveColoring(vertex + 1)) {
return true;
}

this.colors[vertex] = 0; // backtrack
}
}
return false;
}

getSolution() {
if (this.solveColoring()) {
return this.colors;
}
return [];
}
}

export { MColoring }

25 changes: 25 additions & 0 deletions Backtracking/tests/MColoringProblem.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
import { MColoring } from '../MColoringProblem';

describe('MColoringProblem', () => {
it('should color a triangle with 3 colors', () => {
const graph = [
[0, 1, 1],
[1, 0, 1],
[1, 1, 0]
];
const test1 = new MColoring(graph, 3);
const solution = test1.getSolution();
expect(solution).not.toEqual([]);
});

it('should not color a triangle with 2 colors', () => {
const graph = [
[0, 1, 1],
[1, 0, 1],
[1, 1, 0]
];
const test2 = new MColoring(graph, 2);
const solution = test2.getSolution();
expect(solution).toEqual([]);
});
});