forked from adamespii/daily-coding-problem
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathproblem_056.js
65 lines (55 loc) Β· 1.8 KB
/
problem_056.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
// https://github.com/iamvictorli/Daily-Coding-Problem/blob/master/solutions/51-60/Problem56.js
// https://dailycodingproblem.com/blog/graph-coloring/
// Algorithmic Paradigm: BackTracking & Graph Theory
// O(V^K) Time complexity
// O(V) Space complexity
// V is the number of vertices in the graph and K is the number of colors
/**
* Determines whether each vertex in the graph can be colored, such that no two adjacent vertices share the same color using at most k colors.
* @param {number[][]} graph
* @param {number} k
* @return {boolean}
*/
function kColors(graph, k) {
const colors = Array.from(graph.length).fill(-1); // -1 for uncolored
return kColorsHelper(graph, k, colors, 0);
}
/**
* Recursive backtracking helper function. Goes through each vertexNum
* @param {number[][]} graph
* @param {number} k
* @param {number[]} colors
* @param {number} vertexNum
* @return {boolean}
*/
function kColorsHelper(graph, k, colors, vertexNum) {
if (vertexNum === graph.length) return true;
// go through all the colors for vertexNum
for (let i = 1; i <= k; i++) {
if (isValid(graph, colors, vertexNum, i)) {
// choose
colors[vertexNum] = i;
// explore
if (kColorsHelper(graph, k, colors, vertexNum + 1)) return true;
// unchoose
colors[vertexNum] = -1;
}
}
return false;
}
/**
* Determines if the color can be used for vertexNum
* @param {number[][]} graph
* @param {number[]} colors
* @param {number} vertexNum
* @param {number} color
* @return {boolean}
*/
function isValid(graph, colors, vertexNum, color) {
for (let c = 0; c < graph[vertexNum].length; c++) {
const neighbor = graph[vertexNum][c];
// check for valid edge and if the neighbor has the same color
if (neighbor === 1 && colors[c] === color) return false;
}
return true;
}