Ai Assignment - 8 Pycode

You might also like

You are on page 1of 1

import itertools

# Define the graph as an adjacency list for 6 segments


graph = {
'A': ['B', 'C', 'E'],
'B': ['A', 'C', 'D'],
'C': ['A', 'B', 'F'],
'D': ['B'],
'E': ['A'],
'F': ['C']
}

segments = list(graph.keys())
colors = ['R', 'G', 'B']

def is_safe(segment, color, color_assignment):


for neighbor in graph[segment]:
if color_assignment[neighbor] == color:
return False
return True

def graph_coloring(segment_index, color_assignment):


if segment_index == len(segments):
return True # All segments are colored

segment = segments[segment_index]
for color in colors:
if is_safe(segment, color, color_assignment):
color_assignment[segment] = color
if graph_coloring(segment_index + 1, color_assignment):
return True # Continue with the next segment
color_assignment[segment] = None # Backtrack

return False # No valid coloring for the current segment

color_assignment = {segment: None for segment in segments}

if graph_coloring(0, color_assignment):
print("Solution found: Segment colors are as follows:")
for segment, color in color_assignment.items():
print(f"Segment {segment} is colored {color}")
else:
print("No solution exists.")

You might also like