-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathGRAPH COLOURING
40 lines (32 loc) · 1.24 KB
/
GRAPH COLOURING
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
def is_safe(graph, v, c, color, n):
for i in range(n):
if graph[v][i] == 1 and color[i] == c:
return False
return True
def graph_coloring_util(graph, m, color, v, n):
if v == n:
return True #returns true if all vertices are coloured
for c in range(1, m + 1):
if is_safe(graph, v, c, color, n):
color[v] = c
if graph_coloring_util(graph, m, color, v + 1, n): #recursively calls for next vertex
return True #valid coloring was found
color[v] = 0 #function backtracks
def graph_coloring(graph, m):
n = len(graph)
color = [0] * n #array is initialized set to 0 indicating no vertices are coloured initially'
if not graph_coloring_util(graph, m, color, 0, n): #initially set to 0
return None
return color
n = int(input("Enter the number of vertices in the graph: "))
print("Enter the adjacency matrix (0 or 1) for the graph:")
graph = []
for i in range(n):
row = list(map(int, input().split()))
graph.append(row)
m = int(input("Enter the number of colors: "))
result = graph_coloring(graph, m)
if result is not None:
print("Graph Coloring Result:", result)
else:
print(f"No solution found with {m} colors.")