diff --git a/Backtracking/MColoringProblem.js b/Backtracking/MColoringProblem.js index c89f30e04..d625b34a4 100644 --- a/Backtracking/MColoringProblem.js +++ b/Backtracking/MColoringProblem.js @@ -6,44 +6,44 @@ * @see https://en.wikipedia.org/wiki/Graph_coloring */ function mColoring(graph, m) { - const colors = new Array(graph.length).fill(0); + const colors = new Array(graph.length).fill(0) // Check if it's safe to color a vertex with a given color. function isSafe(vertex, color) { for (let i = 0; i < graph.length; i++) { if (graph[vertex][i] && colors[i] === color) { - return false; + return false } } - return true; + return true } // Use backtracking to try and color the graph. function solveColoring(vertex = 0) { if (vertex === graph.length) { - return true; + return true } for (let color = 1; color <= m; color++) { if (isSafe(vertex, color)) { - colors[vertex] = color; - + colors[vertex] = color + if (solveColoring(vertex + 1)) { - return true; + return true } // If no solution, backtrack. - colors[vertex] = 0; + colors[vertex] = 0 } } - return false; + return false } // If coloring is possible, return the colors. if (solveColoring()) { - return colors; + return colors } - return null; + return null } -export { mColoring }; +export { mColoring } diff --git a/Backtracking/tests/MColoringProblem.test.js b/Backtracking/tests/MColoringProblem.test.js index d98134b62..759a328aa 100644 --- a/Backtracking/tests/MColoringProblem.test.js +++ b/Backtracking/tests/MColoringProblem.test.js @@ -1,4 +1,4 @@ -import { mColoring } from '../MColoringProblem'; +import { mColoring } from '../MColoringProblem' describe('MColoringProblem', () => { it('should color a triangle with 3 colors', () => { @@ -6,18 +6,18 @@ describe('MColoringProblem', () => { [0, 1, 1], [1, 0, 1], [1, 1, 0] - ]; - const solution = mColoring(graph, 3); - expect(solution).not.toBeNull(); - }); + ] + const solution = mColoring(graph, 3) + expect(solution).not.toBeNull() + }) it('should not color a triangle with 2 colors', () => { const graph = [ [0, 1, 1], [1, 0, 1], [1, 1, 0] - ]; - const solution = mColoring(graph, 2); - expect(solution).toBeNull(); - }); -}); + ] + const solution = mColoring(graph, 2) + expect(solution).toBeNull() + }) +})