1
+ import random
2
+ import itertools
3
+ import networkx as nx
4
+ import numpy as np
5
+ import matplotlib .pyplot as plt
6
+
7
+ def greedyColoringAlgo (network , colors ):
8
+ nodes = list (network .nodes ())
9
+ random .shuffle (nodes )
10
+ for node in nodes :
11
+ dict_neighbors = dict (network [node ])
12
+ nodes_neighbors = list (dict_neighbors .keys ())
13
+
14
+ forbidden_colors = []
15
+ for neighbor in nodes_neighbors :
16
+ if len (network .nodes .data ()[neighbor ].keys ()) == 0 :
17
+ continue
18
+ else :
19
+ forbidden_color = network .nodes .data ()[neighbor ]
20
+ forbidden_color = forbidden_color ['color' ]
21
+ forbidden_colors .append (forbidden_color )
22
+ for color in colors :
23
+ if color in forbidden_colors :
24
+ continue
25
+ else :
26
+ network .nodes [node ]['color' ] = color
27
+ break
28
+
29
+ ## Create a graph, and an array of colors that has atleast (d+1) colors
30
+ ## Where d is the highest degree of all the vertices.
31
+
32
+ G = nx .Graph ()
33
+ G .add_nodes_from ([1 , 6 ])
34
+ G .add_edges_from ([(1 , 2 ), (1 , 3 ),(1 ,4 ),(1 ,5 ),(1 ,6 )])
35
+ G .add_edges_from ([(2 ,3 ),(2 , 4 ), (2 ,5 ),(2 ,6 )])
36
+ G .add_edges_from ([(3 , 4 ), (3 ,5 ),(3 ,6 )])
37
+ G .add_edges_from ([(4 ,6 )])
38
+ colors = ["red" , "chocolate" , "darkorange" , "moccasin" , "gold" ]
39
+ greedyColoringAlgo (G ,colors )
40
+
41
+ ## Visualization of graph can be done by the code below
42
+ colors_nodes = [data ['color' ] for v , data in G .nodes (data = True )]
43
+ plt .figure (1 ,figsize = (9 ,9 ))
44
+ nx .draw (G , node_color = colors_nodes , with_labels = True )
45
+ plt .show
0 commit comments