×

Chromatic Number in Java

The chromatic number is the bare minimum of colours necessary to accurately colour any graph. To put it another way, the chromatic number can be thought of as the bare minimum of colours required to colour any graph so that no two neighboring vertices of the graph would be given the same colour.

Graph Colouring

The technique of giving colours to a graph's vertices is known as graph colouring. In this case, the two adjacent vertices shouldn't be filled with the same colour. Vertex colouring is another name for graph colouring. When colouring a graph, we must be careful to ensure that no edge's end vertices have the same colour as the rest of the graph. The term "properly coloured graph" refers to this kind of graph.
With some limitations, the chromatic numbers are typically employed to colour graph nodes. The minimal number of distinct colours needed to colour every node in a graph so that any two neighbouring nodes do not share the same colour is given by chromatic numbers in Java. It has numerous applications. The greedy method will be used in this section to determine a graph's chromatic number.

Steps to find Chromatic Number

Step1: Give the graph's first node the first colour.
Step2: For the last N - 1 node, perform the following.
Consider the presently selected node and give it the colour with the lowest colour number. Providing that none of the nodes nearby that have previously been coloured have had the colour applied. Assign a new colour to the node if all previously used colours are present on the nodes that are nearby.

Examples of Chromatic Number

Chromatic Number in Java

Java program for Chromatic Number

import java.util.LinkedList;  
import java.util.*;  
import java.io.*;  


//The class displays an adjacency list-based undirected graph.
public class sol
{  
private int S; // Number of nodes  
private LinkedList<Integer>adjList[]; //Adjacency List  


//Constructor  
sol(int s)  
{  
S = s;  
adjList = new LinkedList[s];  
for (int i = 0; i< n; i++)  
{  
adjList[i] = new LinkedList();  
}  
}  


// Method to create an edge into the graph from node x to y and y to x  
void addingE(int a, int b)  
{  
// The Graph is not directed  
adjList[a].add(b);  
adjList[b].add(a);   
}  




// A method that finds the chromatic number of a graph  
void findChromticNo(int arr[])  
{  
// caculating the size of the array  
int size = arr.length;  
Set<Integer>hashSet = new HashSet<Integer>();  


// iterating over every node and storing its color in the hashset
for(int j = 0; j < size; j++)  
{  
// hashset only contains unique numbers.  
hashSet.add(arr[j]);  
}  


// finding the chromatic Number of the graph  
int chromaticNumber = hashSet.size();  


System.out.println("chromatic no of the graph is: " + chromaticNumber);  


}  


void greedyColorNodes()  
{  
int res[] = new int[S];  


Arrays.fill(res, -1);  


res[0] = 0;  


booleanavail[] = new boolean[N];  


Arrays.fill(avail, true);  


// Assign colors to theh remaining S - 1 nodes  
for (int s = 1; s<S; s++)  
{  
Iterator<Integer>itr = adjList[s].iterator() ;  
while (itr.hasNext())  
{  
int i = itr.next();  
if (res[i] != -1)  
    avail[res[i]] = false;  
}  


// Find the first color that is available  
int clr;  
for (clr = 0; clr< N; clr++)  
{  
if (avail[clr])  
{  
break;  
}  
}  


res[s] = clr; // Assigning the found color  


// For the next iteration, resetting the values back to true   
Arrays.fill(avail, true);  
}  


// printing the result  
for (int s = 0; s<S; s++)  
{  
// N->node and C->colour
System.out.println("N " + s + " ---> C - " + res[s]);  
}  
// for finding the chromatic number of the graph  
findChromticNo(res);  
}  
// main method  
public static void main(String argvs[])  
{  
// creating a graph that contains   
// 5 nodes  
Graphs g = new Graphs(5);  


// creating edges between nodes  
g.addingE(0,1);  
g.addingE(0, 1);  
g.addingE(1, 2);  
g.addingE(1, 3);  
g.addingE(2, 1);  
g.addingE(3, 4);  


System.out.println("Coloring g is: ");  


// invoking the method greedyColorNodes() to color the nodes  
g.greedyColorNodes();  


System.out.println();  


// creating a graph that contains   
// 4 nodes  
Graphs g2 = new Graphs(4);  


System.out.println("Coloring g2 is: ");  


// creating edges between nodes  
g2.addingE(0, 1);  
g2.addingE(0, 2);  
g2.addingE(1, 3);  
g2.addingE(2, 3);  


// invoking the method greedyColorNodes() to color the nodes  
g2.greedyColorNodes();  


  } 
}  

Output:

Coloring g is: 
N 0 ---> C - 0
N 1 ---> C - 1
N 2 ---> C - 2
N 3 ---> C - 0
N 4 ---> C - 1
chromatic number of the graph is: 3


Coloring of the g2 is: 
Node 0 ---> Color - 0
Node 1 ---> Color - 1
Node 2 ---> Color - 1
Node 3 ---> Color - 0
The chromatic number of the graph is: 2
Chromatic Number in Java
Chromatic Number in Java

Java Program to find Chromatic Index

import java.util.*;


public class CI {


    // method to find the chromatic index
    public void edgeColoring(int[][] e, int x)
    {
        // declare a edge to firstedge and color to color 1
        int i = 0, color = 1;


        // Continue until all the edges have been coloured.
        while (i<x) {
            // Give the selected edge a color
            e[i][2] = color;
boolean flag = false;
            // Check by iterating through all other edges.
            for (int j = 0; j < e; j++) {
                // Ignore if same edge
                if (j == i)
                    continue;
                // See if one vertex resembles another.
                if ((e[i][0] == e[j][0])
                    || (e[i][1] == e[j][0])
                    || (e[i][0] == e[j][1])
                    || (e[i][1] == e[j][1])) {
                    // Check if color is similar
                    if (e[i][2] == e[j][2]) {
                        // Increase the color by 1
                        color++;
                        flag = true;
                        break;
                    }
                }
            }


            // If same color faced then repeat again
            if (flag == true) {
                continue;
            }


// / Alternatively, go to a new vertex with colour 1 if not
            color = 1;
i++;
        }


        // Check the maximum color from all the edge colors
        int maxColor = -1;
        for (i = 0; i<x; i++) {
maxColor = Math.max(maxColor, edges[i][2]);
        }


        // Print the chromatic index
System.out.println("Chromatic Index = " + maxColor);
    }


    // Driver code
    public static void main(String[] args)
    {


        // Number of edges
        int x = 4;


        // Edge list
int[][] e = new int[x][3];


        // Initialize all edge colors to 0
        for (int i = 0; i< e; i++) {
            e[i][2] = -1;
        }


        // Edges
e[0][0] = 1;
e[0][1] = 2;


e[1][0] = 2;
e[1][1] = 3;


e[2][0] = 3;
e[2][1] = 4;


e[3][0] = 4;
e[3][1] = 1;


        // Run the function
chromaticIndexy = new chromaticIndex();
y.edgeColoring(e, x);
    }
}

Output:

chromatic Index = 2

Applications of Chromatic Number

  1. Time table or making schedule:
    Imagine having to design a college or university's exam timetable. The individual is knowledgeable about every subject and the pupils enrolled in it. One simple scheduling method is to hold exams for just one subject during a single time frame. As a result, the entire time window will be determined by the total number of available subjects. Such scheduling is ineffective, though, as fewer time periods must be available.
    Additionally, it is impossible to arrange all of the exams during a single time period. The reason for this is that a student could enrol in several different subjects. If all of those topics' tests are scheduled for the same time slot, the student can only take the exam for that one subject; the other exams must be missed.
    Therefore, it is necessary to reduce the time slots so that there are no conflicts. We use the graph colouring method to do this. The subjects are viewed as nodes, and the only way an edge can exist between two nodes is if a single student is enrolled in both of those subjects. Find the graph's chromatic number after building it. The minimum time periods necessary to correctly administer the exam are indicated by the chromatic number.
  2. Assignment of mobile radio frequency:
    The frequencies assigned to each tower must differ when they are all designated at the same site to serve as mobile towers. We require the aid of chromatic numbers to assign the frequencies under this restriction, and the number of frequencies should also be the minimal.
    The towers can be thought of as nodes, and an edge connecting these two nodes demonstrates that the towers are close to one another. This is the classic graph colouring problem, where we must lessen the total number of distinct colours, which is determined by the graph's chromatic number.

Related Topics

Packages Program in java

Let us know what package is in the Java programming language, and later we will learn about types of packages and how to define a package. How to import Java...

4 minutes read.

Matrix Multiplication Program in Java

Matrix Multiplication Program in Java The matrix multiplication program in Java is the continuation of the matrix program in Java that we have already discussed earlier. In this section, we will...

3 minutes read.

How to Import Packages in Java

To know about the importing the packages of Java, we need to understand about how to packages work. Packages The package in Java is a collection of Classes and Interfaces. The packages...

3 minutes read.

Null Pointer Exception in Java

It is a runtime error exception. The null value is allocated to the object reference in this exception. We will explicitly throw this null pointer exception when the program wants...

3 minutes read.

Java Integer highestOneBit()

The highestOneBit() method of Java Integer class returns an int value with at most a single one-bit, in the position of the highest-order one-bit in the specified int value.  Syntax public static...

1 minute read.

PriorityBlockingQueue Class in Java

What is the Queue? An abstract data structure like Stacks is a queue. A queue is open on both ends. Data is always pushed to one end, called enqueue, and removed...

4 minutes read.

Java String concat() method:

Java String concat() method is used to add the given String to the end of the current String. Syntax: public String concat(String str) Parameter: Str: String to be concatenated at the end of current...

1 minute read.

Two Decimal Places Java

When a double data type is used in Java before a variable, this indicates 15 digits after decimal point. However, there are situations when we only require 2 decimal places...

4 minutes read.

Pernicious Number in Java

If the number of 1s in a number appearing in the binary representation is the prime number, such a number is known as a pernicious number. A pernicious number always corresponds to...

4 minutes read.

Three Partition Problems in Java

In talks with leading IT organizations like Google, Amazon, TCS, Accenture, etc., this extremely intriguing subject is constantly brought up. The goal of the problem-solving exercise is to evaluate the...

8 minutes read.

Java Integer toOctalString() method

The toOctalString() method of Java Integer class returns a string representing the specified int argument as an unsigned integer in base 8. Syntax public static String toOctalString (int  i) Parameters The parameter ‘i’ represents...

1 minute read.

Volatile keyword in Java

Multiple threads can change a variable's value by using the volatile keyword. Making classes thread-safe is another application for it. It indicates that using a method or an instance of...

3 minutes read.

Java ArrayList

Java ArrayList Class A Java ArrayList class is a dynamic array which is used to store the elements. It is a part of collection framework. It implements the List Interface and inherits the...

12 minutes read.

Application of Array in Java

In this article we are going to acknowledge about what the array is, types of arrays and their applications. What is an array? An array is often a set of interrelated elements...

4 minutes read.

How to Change the Day in the Date using Java?

To operate with the date and time in Java, we need the Calendar abstract class. It provides a number of helpful interfaces that enable us to convert dates between a...

4 minutes read.

How to Reverse a String in Java

How to Reverse a String in Java There are a lot of ways to reverse a string in Java. One can use iteration, StringBuilder, StringBuffer to do the reverse of a...

6 minutes read.

Creation of Multi Thread in java

What are threads in Java? We can use threads to facilitate parallel processing. Threads are helpful when you wish to execute several pieces of code concurrently. A thread is a small process...

3 minutes read.

Java String equals() method

equals() method compares two string based on the their content. Syntax public boolean equals(Objects anObject) parameter anObject: Object to be compared with the current String. Returns It returns true when the current String is equivalent to...

1 minute read.

Recursion Program in Java

The recursion program in Java demonstrates the usage of recursion. The process by which a function/ method calls itself, again and again, is called recursion. Each recursive call is pushed...

10 minutes read.

JDBC Architecture

JDBC: JDBC stands for Java Database Connectivity. Sun Microsystems has a specification called JDBC. JDBC is a Java API (Application Programming Interface) that enables users to interact or communicate with...

4 minutes read.