Find Chromatic Number in Python
Last Updated :
12 Apr, 2024
Find the chromatic number of a given graph G, which is the smallest number of colors needed to color the vertices of the graph in such a way that no two adjacent vertices share the same color.
Examples:
Input: Vertices = 5, Edges: [(0, 1), (0, 2), (1, 2), (1, 3), (2, 3), (3, 4)]
Output: Chromatic Number: 3
Input: Vertices = 4, Edges: [(0, 1), (0, 2), (1, 2), (1, 3), (2, 3)]
Output: Chromatic Number: 2
Chromatic Number in Python Using Greedy Algorithm:
Assign colors to vertices of the graph in the order of their degrees. Always assign the smallest possible color that hasn't been used by its neighbors.
Steps-by-step algorithm:
- Initialize an empty dictionary
color_map
to store the color of each vertex. - Sort the vertices based on their degrees in non-increasing order.
- For each vertex, assign the smallest possible color that hasn't been used by its neighbors.
- Return the number of unique colors used.
Below is the implementation of the above approach:
Python3
class Graph:
def __init__(self, vertices):
self.V = vertices
self.graph = [[] for _ in range(vertices)]
def add_edge(self, u, v):
self.graph[u].append(v)
self.graph[v].append(u)
def greedy_coloring(self):
color_map = {}
# Sort vertices by their degrees in non-increasing order
vertices_degrees = [(len(self.graph[i]), i) for i in range(self.V)]
vertices_degrees.sort(reverse=True)
# Assign colors to vertices
for _, vertex in vertices_degrees:
neighbor_colors = {color_map.get(neigh) for neigh in self.graph[vertex]}
color_map[vertex] = next(color for color in range(self.V) if color not in neighbor_colors)
# Return the number of unique colors used
return len(set(color_map.values()))
# Example Usage
g = Graph(5)
g.add_edge(0, 1)
g.add_edge(0, 2)
g.add_edge(1, 2)
g.add_edge(1, 3)
g.add_edge(2, 3)
g.add_edge(3, 4)
print(g.greedy_coloring()) # Output: 3
Time Complexity: O(V+E), where V is the number of vertices and E is the number of edges.
Auxiliary Space: O(V) for the color map dictionary.
Use a backtracking approach to try different colorings recursively, keeping track of the chromatic number.
Step-by-step algorithm:
- Define a recursive function
color_graph
that tries to color the graph using a given number of colors. - For each vertex, try coloring it with each available color.
- If a coloring is found where no two adjacent vertices share the same color, recursively try to color the remaining vertices.
- Return the minimum number of colors needed to color the graph.
Below is the implementation of the above approach:
Python3
class Graph:
# Constructor to intialize the graph
def __init__(self, vertices):
self.V = vertices
self.graph = [[] for _ in range(vertices)]
# Function to add an undirected edge in Python
def add_edge(self, u, v):
self.graph[u].append(v)
self.graph[v].append(u)
# Function to check whether it is safe to color the vertex
# with the given color such that none of the eighbor has the same color
def is_safe(self, vertex, color, color_map):
for neighbor in self.graph[vertex]:
if color_map.get(neighbor) == color:
return False
return True
# Function to color the graph with num_colors
def color_graph(self, vertex, num_colors, color_map):
if vertex == self.V:
return True
for color in range(num_colors):
if self.is_safe(vertex, color, color_map):
color_map[vertex] = color
if self.color_graph(vertex + 1, num_colors, color_map):
return True
color_map[vertex] = -1
return False
# Function to find the chromatic number of the graph
def backtracking_coloring(self):
# Initialize color map with -1 for uncolored vertices
color_map = {-1: -1}
num_colors = 1
while not self.color_graph(0, num_colors, color_map):
num_colors += 1
color_map = {-1: -1}
return num_colors
# Example Usage
g = Graph(5)
g.add_edge(0, 1)
g.add_edge(0, 2)
g.add_edge(1, 2)
g.add_edge(1, 3)
g.add_edge(2, 3)
g.add_edge(3, 4)
print(g.backtracking_coloring()) # Output: 3
Time Complexity: Exponential, O(kn), where k is the number of colors and n is the number of vertices.
Auxiliary Space: O(n) for the recursion stack and the color map dictionary.
Related Articles:
Similar Reads
M-Coloring Problem in Python M-Coloring Problem is a classic algorithmic problem which involves coloring the vertices of a graph using at most M different colors such that no two adjacent vertices share the same color. We are given a graph and an integer M, determine if it's possible to color the graph using M colors such that
4 min read
Chromatic Number of a Graph | Graph Colouring Graph coloring is a fundamental concept in graph theory, and the chromatic number is a key parameter that quantifies the coloring properties of a graph. Let's go into the introductory aspects of the chromatic number.Graph coloring refers to the problem of coloring vertices of a graph in such a way t
15+ min read
Convert RGB to Color Names in Python Converting RGB values to color names is a common task in various applications, from web development to image processing. While RGB values are precise, human-readable color names can make your code and output more understandable. This article will guide you through the process of converting RGB value
4 min read
Complete Graph using Networkx in Python A complete graph also called a Full Graph it is a graph that has n vertices where the degree of each vertex is n-1. In other words, each vertex is connected with every other vertex. Example: Complete Graph with 6 edges: C_G6 Properties of Complete Graph: The degree of each vertex is n-1.The total nu
3 min read
How to invert colors of an image in pygame? In this article, we are going to learn how to invert the colors of an image using Pygame in Python programming language. Pygame is a multiplatform Python module and framework designed for creating video games in Python. It includes several libraries that manage audio and visuals. Right now, Pygame i
7 min read
Python Pillow - Colors on an Image In this article, we will learn Colors on an Image using the Pillow module in Python. Let's discuss some concepts: A crucial class within the Python Imaging Library is the Image class. It's defined within the Image module and provides a PIL image on which manipulation operations are often administere
4 min read
Built-in Continuous Color Scales in Python Plotly Plotly has built-in discrete and continuous color scales. This article is about discrete color scales. A color continuous scale input is accepted by several Plotly Express functions, and many trace types have a color scale property in their schema. Plotly has a wide variety of built-in continuous co
3 min read
Ladder Graph Using Networkx Module in Python In this article, we are going to see the ladder graph using Python. It is a graph that looks like ladders used commonly with every node attached to two other nodes in a specific manner. We can obtain a ladder graph by joining two-path graphs of n nodes each by each node connected with a correspondin
2 min read
Color Identification in Images using Python - OpenCV An open-source library in Python, OpenCV is basically used for image and video processing. Not only supported by any system, such as Windows, Linux, Mac, etc. but also it can be run in any programming language like Python, C++, Java, etc. OpenCV also allows you to identify color in images. Donât you
3 min read
Graph Coloring Algorithm in Python Given an undirected graph represented by an adjacency matrix. The graph has n nodes, labeled from 1 to n. The task is to assign colors to each node in such a way that no two adjacent nodes have the same color. The challenge is to solve this problem using the minimum number of colors. Graph Coloring
8 min read