Coloring a Cycle Graph
Last Updated :
02 Sep, 2022
Cycle:- cycle is a path of edges and vertices wherein a vertex is reachable from itself. or in other words, it is a Closed walk.
Even Cycle:- In which Even number of vertices is present is known as Even Cycle.
Odd Cycle:- In which Odd number of Vertices is present is known as Odd Cycle.
Given the number of vertices in a Cyclic Graph. The task is to determine the Number of colors required to color the graph so that No two Adjacent vertices have the same color.
Approach:
If the no. of vertices is Even then it is Even Cycle and to color such graph we require 2 colors.
If the no. of vertices is Odd then it is Odd Cycle and to color such graph we require 3 colors.
Examples:
Input : vertices = 3
Output : No. of colors require is: 3
Input : vertices = 4
Output : No. of colors require is: 2
Example 1: Even Cycle: Number of vertices = 4
Color required = 2
Example 2: Odd Cycle: Number of vertices = 5
Color required = 3
Implementation:
C++
#include <bits/stdc++.h>
using namespace std;
int Color( int vertices)
{
int result = 0;
if (vertices % 2 == 0)
result = 2;
else
result = 3;
return result;
}
int main()
{
int vertices = 3;
cout << "No. of colors require is: " << Color(vertices);
return 0;
}
|
Java
import java.io.*;
class GFG {
static int Color( int vertices)
{
int result = 0 ;
if (vertices % 2 == 0 )
result = 2 ;
else
result = 3 ;
return result;
}
public static void main (String[] args)
{
int vertices = 3 ;
System.out.println( "No. of colors require is: " + Color(vertices));
}
}
|
Python3
def Color(vertices):
result = 0
if (vertices % 2 = = 0 ):
result = 2
else :
result = 3
return result
if __name__ = = '__main__' :
vertices = 3
print ( "No. of colors require is:" ,Color(vertices))
|
C#
using System;
class GFG
{
static int Color( int vertices)
{
int result = 0;
if (vertices % 2 == 0)
result = 2;
else
result = 3;
return result;
}
public static void Main ()
{
int vertices = 3;
Console.WriteLine( "No. of colors required is: " +
Color(vertices));
}
}
|
PHP
<?php
function Color( $vertices )
{
$result = 0;
if ( $vertices % 2 == 0)
$result = 2;
else
$result = 3;
return $result ;
}
$vertices = 3;
echo "No. of colors required is: " ,
Color( $vertices );
?>
|
Javascript
<script>
function Color(vertices)
{
var result = 0;
if (vertices % 2 == 0)
result = 2;
else
result = 3;
return result;
}
var vertices = 3;
document.write( "No. of colors require is: " +
Color(vertices));
</script>
|
Output
No. of colors require is: 3
Complexity Analysis:
- Time Complexity: O(1)
- Space Complexity: O(1)
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...