Skip to content

Commit 9459a4f

Browse files
m Coloring Problem
1 parent 098cb10 commit 9459a4f

File tree

1 file changed

+44
-0
lines changed

1 file changed

+44
-0
lines changed

Backtracking/mcoloring.py

+44
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
class Graph():
2+
3+
def __init__(self, vertices):
4+
self.V = vertices
5+
self.graph = [[0 for column in range(vertices)]\
6+
for row in range(vertices)]
7+
8+
# A utility function to check if the current color assignment
9+
# is safe for vertex v
10+
def isSafe(self, v, colour, c):
11+
for i in range(self.V):
12+
if self.graph[v][i] == 1 and colour[i] == c:
13+
return False
14+
return True
15+
16+
# A recursive utility function to solve m
17+
# coloring problem
18+
def graphColourUtil(self, m, colour, v):
19+
if v == self.V:
20+
return True
21+
22+
for c in range(1, m+1):
23+
if self.isSafe(v, colour, c) == True:
24+
colour[v] = c
25+
if self.graphColourUtil(m, colour, v+1) == True:
26+
return True
27+
colour[v] = 0
28+
29+
def graphColouring(self, m):
30+
colour = [0] * self.V
31+
if self.graphColourUtil(m, colour, 0) == False:
32+
return False
33+
34+
# Print the solution
35+
print "Solution exist and Following are the assigned colours:"
36+
for c in colour:
37+
print c,
38+
return True
39+
40+
# Driver Code
41+
g = Graph(4)
42+
g.graph = [[0,1,1,1], [1,0,1,0], [1,1,0,1], [1,0,1,0]]
43+
m=3
44+
g.graphColouring(m)

0 commit comments

Comments
 (0)