Created
August 1, 2019 17:49
-
-
Save verdi327/9f867c0f7e0382765eacf8ea6a2b1c90 to your computer and use it in GitHub Desktop.
graph-coloring
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class GraphNode { | |
constructor(label) { | |
this.label = label; | |
this.neighbors = new Set(); | |
this.color = null; | |
} | |
} | |
const nodeA = new GraphNode('A'); | |
const nodeB = new GraphNode('B'); | |
const nodeC = new GraphNode('C'); | |
const nodeD = new GraphNode('D'); | |
nodeA.neighbors.add(nodeB); | |
nodeB.neighbors.add(nodeA); | |
nodeB.neighbors.add(nodeC); | |
nodeC.neighbors.add(nodeB); | |
nodeC.neighbors.add(nodeD); | |
nodeD.neighbors.add(nodeC); | |
const graph = [nodeA, nodeB, nodeC, nodeD]; | |
const colors = ['red', 'green']; | |
function colorGraph(graph, colors) { | |
const queue = [graph[0]]; | |
let index = 0; | |
let currentGraph; | |
while (queue.length) { | |
currentGraph = queue.pop(); | |
if (!currentGraph.color) { | |
currentGraph.color = colors[index]; | |
index++; | |
if (index === colors.length) index = 0; | |
} | |
currentGraph.neighbors.forEach(neighbor => { | |
if (neighbor.label === currentGraph.label) throw new Error('loop graphs are invalid'); | |
if (!neighbor.color) { | |
queue.push(neighbor); | |
} | |
}); | |
} | |
return graph; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment