forked from TheAlgorithms/Python
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathm_coloringproblem.py
89 lines (66 loc) · 1.91 KB
/
m_coloringproblem.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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
# Python3 program for the above approach
# Number of vertices in the graph
# define 4 4
# check if the colored
# graph is safe or not
def isSafe(graph, color):
# check for every edge
for i in range(4):
for j in range(i + 1, 4):
if graph[i][j] and color[j] == color[i]:
return False
return True
# /* This function solves the m Coloring
# problem using recursion. It returns
# false if the m colours cannot be assigned,
# otherwise, return true and prints
# assignments of colours to all vertices.
# Please note that there may be more than
# one solutions, this function prints one
# of the feasible solutions.*/
def graphColoring(graph, m, i, color):
# if current index reached end
if i == 4:
# if coloring is safe
if isSafe(graph, color):
# Print the solution
printSolution(color)
return True
return False
# Assign each color from 1 to m
for j in range(1, m + 1):
color[i] = j
# Recur of the rest vertices
if graphColoring(graph, m, i + 1, color):
return True
color[i] = 0
return False
# /* A utility function to print solution */
def printSolution(color):
print("Solution Exists:" " Following are the assigned colors ")
for i in range(4):
print(color[i], end=" ")
# Driver code
if __name__ == "__main__":
# /* Create following graph and
# test whether it is 3 colorable
# (3)---(2)
# | / |
# | / |
# | / |
# (0)---(1)
# */
graph = [
[0, 1, 1, 1],
[1, 0, 1, 0],
[1, 1, 0, 1],
[1, 0, 1, 0],
]
m = 3 # Number of colors
# Initialize all color values as 0.
# This initialization is needed
# correct functioning of isSafe()
color = [0 for i in range(4)]
# Function call
if not graphColoring(graph, m, 0, color):
print("Solution does not exist")