Created
November 28, 2023 11:31
-
-
Save carefree-ladka/5fa1788aecceed8ebce55f55a6869553 to your computer and use it in GitHub Desktop.
Graph Coloring in JavaScript
This file contains hidden or 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 Graph { | |
| constructor() { | |
| this.adjList = new Map(); | |
| } | |
| addVertex = (v) => { | |
| if (!this.adjList.has(v)) { | |
| this.adjList.set(v, []); | |
| } | |
| }; | |
| addEdge = (v, u) => { | |
| this.adjList.get(v).push(u); | |
| this.adjList.get(u).push(v); | |
| }; | |
| coloring = () => { | |
| const colored = new Map(); // Map to store vertex-color pairs | |
| const colors = ["red", "green", "blue", "yellow", "orange", "purple"]; // Array of available colors | |
| for (const key of this.adjList.keys()) { | |
| const adjColors = new Set(); | |
| this.adjList.get(key).forEach((adjVertex) => { | |
| if (colored.has(adjVertex)) { | |
| adjColors.add(colored.get(adjVertex)); | |
| } | |
| }); | |
| for (const color of colors) { | |
| if (!adjColors.has(color)) { | |
| colored.set(key, color); | |
| break; | |
| } | |
| } | |
| } | |
| return [...colored] | |
| }; | |
| } | |
| const graph = new Graph(); | |
| ["A", "B", "C", "D", "E", "F"].forEach((vertex) => graph.addVertex(vertex)); | |
| graph.addEdge("A", "B"); | |
| graph.addEdge("A", "C"); | |
| graph.addEdge("B", "C"); | |
| graph.addEdge("B", "D"); | |
| graph.addEdge("C", "D"); | |
| graph.addEdge("C", "E"); | |
| graph.addEdge("D", "E"); | |
| graph.addEdge("E", "F"); | |
| console.log(graph.coloring()); | |
| /* | |
| [ | |
| [ 'A', 'red' ], | |
| [ 'B', 'green' ], | |
| [ 'C', 'blue' ], | |
| [ 'D', 'red' ], | |
| [ 'E', 'green' ], | |
| [ 'F', 'red' ] | |
| ] | |
| */ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment