mirror of
https://github.com/TheAlgorithms/JavaScript.git
synced 2025-07-07 11:08:54 +08:00
chore: format using prettier
This commit is contained in:

committed by
Rak Laptudirm

parent
0b9fad86ba
commit
28c27d9474
@ -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 }
|
||||
|
Reference in New Issue
Block a user