-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBACK TRACKING ALGORITHM:
67 lines (62 loc) · 2.42 KB
/
BACK TRACKING ALGORITHM:
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
66
import numpy as np
import networkx as nx
import matplotlib.pyplot as plt
import time
def draw_graph(hubungan,color): #untuk menampilkan graph
t = time.process_time()
G=nx.Graph()
G.add_edges_from(hubungan)
co = [color[i] for i in G.nodes()]
nx.draw(G, node_size=1000/(len(hubungan)/10),node_color=co,
with_labels=True,font_color='white')
print(time.process_time()-t)
plt.show()
#-------------------------- inti program begin -------------------------
def isSafe(co,list_color,n):
for i in range(node-1): #untuk setiap node lain
if adj_mtx[n][i] == 1 and list_color[i] == co: #jikabertetangga dan warnanya sama
return False
return True
def findSolution(list_color,n):
if(n == node): #kalo udah semua node di warnai
return True
for co in range(1,mc+1): #coba setiap warna
if(isSafe(co,list_color,n)): #if warna bisa di pakai
list_color[n] = co #assign dengan warna co
if findSolution(list_color,n+1): #pindah ke node lain
return True
list_color[n] = 0 #kalo gabisa, hapus warna sekarang
return False
def graphColoring(mtx,mc):
list_color = np.zeros(node,dtype=int)
print('>> Maximum color :', mc)
if not(findSolution(list_color,0)): #kalo ga ada solusi
print('>> Solution not found')
return False
print('>> Solution Found :',list_color)
print('>> Minimum color needed :', max(list_color))
draw_graph(hubungan,list_color)
#-------------------------- inti program ends ------------------------------
adj_mtx = [[0,1,1,0,0,0,0,0,0,0,0,0,0],
[1,0,0,0,1,0,0,0,0,0,0,0,0],
[1,0,0,1,1,0,0,0,0,0,0,0,0],
[0,0,1,0,0,1,0,0,0,0,0,0,0],
[0,1,0,0,0,1,0,0,0,0,0,0,0],
[0,0,0,1,1,0,1,1,0,0,0,0,0],
[0,0,0,0,0,1,0,0,1,0,0,0,0],
[0,0,0,0,0,1,0,0,0,1,0,0,0],
[0,0,0,0,0,0,1,0,0,1,1,0,0],
[0,0,0,0,0,0,0,1,1,0,0,1,0],
[0,0,0,0,0,0,0,0,1,0,0,0,1],
[0,0,0,0,0,0,0,0,0,1,0,0,1],
[0,0,0,0,0,0,0,0,0,0,1,1,0]]
node = len(adj_mtx)
print(adj_mtx)
#cari keterhubungan
hubungan = []
for i in range(len(adj_mtx)):
for j in range(len(adj_mtx[i])):
if adj_mtx[i][j] == 1 and (i,j) not in hubungan and (j,i) not in hubungan:
hubungan.append((i,j))
mc = node #max color
graphColoring(adj_mtx,mc)