-
Notifications
You must be signed in to change notification settings - Fork 2
/
color_simple.py
64 lines (52 loc) · 1.41 KB
/
color_simple.py
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
# -*- coding: utf-8 -*-
"""
Graphs: puzzles
Coloration: simple algorithms
"""
from algopy import graph
def __testColor(G, colors):
for s in range(G.order):
for adj in G.adjlists[s]:
if colors[s] == colors[adj]:
print(s, adj)
return False
return True
def __degrees(G):
d = [0]*G.order
for s in range(G.order):
d[s] = (len(G.adjlists[s]), s)
return d
# greedy algorithm
def colorgreedy(G):
colors = [None] * G.order
colors[0] = 1
nb = 1
for s in range(1, G.order):
col = [0] * (nb+1)
for adj in G.adjlists[s]:
if colors[adj]:
col[colors[adj]] += 1
i = 1
while i < nb+1 and col[i] != 0:
i += 1
colors[s] = i
nb = max(nb, i)
return nb, colors
# Welsh-Powell algorithm
def Welsh_Powell(G):
deg = __degrees(G)
deg.sort(reverse=True)
colors = [0] * G.order
col = 1
nb = 0
for (_, s) in deg:
if colors[s] == 0:
colors[s] = col
L = G.adjlists[s]
nb += 1
for notAdj in range(G.order):
if colors[notAdj] == 0 and (notAdj not in L):
colors[notAdj] = col
L = L + G.adjlists[notAdj]
col += 1
return (col-1, colors)