Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Interview Problems on Graph
  • Practice Graph
  • MCQs on Graph
  • Graph Tutorial
  • Graph Representation
  • Graph Properties
  • Types of Graphs
  • Graph Applications
  • BFS on Graph
  • DFS on Graph
  • Graph VS Tree
  • Transpose Graph
  • Dijkstra's Algorithm
  • Minimum Spanning Tree
  • Prim’s Algorithm
  • Topological Sorting
  • Floyd Warshall Algorithm
  • Strongly Connected Components
  • Advantages & Disadvantages
Open In App
Next Article:
Chromatic Number of a Graph | Graph Colouring
Next article icon

Find Chromatic Number in Python

Last Updated : 12 Apr, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

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:

  1. Initialize an empty dictionary color_map to store the color of each vertex.
  2. Sort the vertices based on their degrees in non-increasing order.
  3. For each vertex, assign the smallest possible color that hasn't been used by its neighbors.
  4. 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 

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.

Find Chromatic Number in Python Using Backtracking Algorithm:

Use a backtracking approach to try different colorings recursively, keeping track of the chromatic number.

Step-by-step algorithm:

  1. Define a recursive function color_graph that tries to color the graph using a given number of colors.
  2. For each vertex, try coloring it with each available color.
  3. If a coloring is found where no two adjacent vertices share the same color, recursively try to color the remaining vertices.
  4. 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 

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:

  • Introduction to Graph Coloring
  • M-Coloring Problem
  • Graph Coloring Using Greedy Algorithm
  • Edge Coloring of a Graph
  • Coloring a Cycle Graph
  • Chromatic Polynomial

Next Article
Chromatic Number of a Graph | Graph Colouring

C

code_r
Improve
Article Tags :
  • Graph
  • DSA
  • Python-DSA
Practice Tags :
  • Graph

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
    15+ min read
  • Python Counter| Find duplicate rows in a binary matrix
    Given a binary matrix whose elements are only 0 and 1, we need to print the rows which are duplicate of rows which are already present in the matrix. Examples: Input : [[1, 1, 0, 1, 0, 1], [0, 0, 1, 0, 0, 1], [1, 0, 1, 1, 0, 0], [1, 1, 0, 1, 0, 1], [0, 0, 1, 0, 0, 1], [0, 0, 1, 0, 0, 1]] Output : (1
    2 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: Properties of Complete Graph: The degree of each vertex is n-1.The total number
    3 min read
  • CIE Chromaticity Diagram in Computer Graphics
    The chromaticity diagram represents the spectral colours and their mixtures based on the values of the primary colours(i.e Red, Green, Blue) contained by them. Chromaticity contains two parameters i.e, hue and saturation. When we put hue and saturation together then it is known as Chrominance. Chrom
    2 min read
  • Matplotlib.pyplot.colorbar() function in Python
    The matplotlib.pyplot.colorbar() function in Python adds a color scale (color bar) to a plot, helping to interpret the relationship between data values and colors in colormapped plots like imshow(), scatter() or contourf(). Let us see an example to understand this better: [GFGTABS] Python import num
    4 min read
  • Creating a Path Graph Using Networkx in Python
    A path graph is a connected graph denoted by Pn if it contains n nodes. Nodes are connected in form of a straight line in a path graph. Here we will discuss how networkx module can be used to generate one using its inbuilt path_graph() function. Properties of Path Graph:The number of nodes in a path
    2 min read
  • Painting Fence Algorithm in Python
    Given a fence with n posts and k colors, find out the number of ways of painting the fence such that at most 2 adjacent posts have the same color. Since the answer can be large, return it modulo 10^9 + 7. Input : n = 2 k = 4Output : 16Explanation: We have 4 colors and 2 posts.Ways when both posts ha
    3 min read
  • Program to find Star number
    A number is termed as star number, if it is a centered figurate number that represents a centered hexagram (six-pointed star) similar to chinese checker game. The few star numbers are 1, 13, 37, 73, 121, 181, 253, 337, 433, ....Examples: Input : n = 2 Output : 13 Input : n = 4 Output : 73 Input : n
    3 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences