Ai 3 Exp
Ai 3 Exp
Experiment - 3
Name: Anoop Khude Roll No: 05
AIM
write a program to implement Graph Coloring
Theory/Procedure/Algorithm
Graph coloring refers to the problem of coloring vertices of a graph in such a way that no two
adjacent vertices have the same color. This is also called the vertex coloring problem. If coloring is
done using at most m colors, it is called m-coloring.
Auxiliary Space: O(V). The Recursive Stack of graph coloring(…) function will require O(V) space.
Assign colors one by one to different vertices, starting from vertex 0. Before assigning a color, check
for safety by considering already assigned colors to the adjacent vertices i.e check if the adjacent
vertices have the same color or not. If there is any color assignment that does not violate the
conditions, mark the color assignment as part of the solution. If no assignment of color is possible
then backtrack and return false
Bharati Vidyapeeth (Deemed to be University)
Department of Engineering and Technology, Kharghar, Navi
Mumbai
Code:
print("Anoop Khude")
class Graph:
def __init__(self, vertices):
self.V = vertices
self.graph = [[] for _ in range(vertices)]
def greedy_coloring(self):
result = [-1] * self.V
result[0] = 0
available = [False] * self.V
result[u] = color
for v in self.graph[u]:
if result[v] != -1:
available[result[v]] = False
for u in range(self.V):
print(f"Vertex {u} --> Color {result[u]}")
if __name__ == "__main__":
graph = Graph(5)
Bharati Vidyapeeth (Deemed to be University)
Department of Engineering and Technology, Kharghar, Navi
Mumbai
print("Coloring of vertices:")
graph.greedy_coloring()
Output:
Bharati Vidyapeeth (Deemed to be University)
Department of Engineering and Technology, Kharghar, Navi
Mumbai
Conclusion
Assessment