Vertex Cover

You might also like

Download as txt, pdf, or txt
Download as txt, pdf, or txt
You are on page 1of 3

import java.util.

HashSet;
import java.util.Set;
public class VerexCover
{
private static final char[] name_vertex = { 'A', 'B', 'C', 'D', 'E', 'F'
,'G', 'H', 'I', 'J' };
private static final int[][] matrix = { { 0, 1, 0, 1, 1 },{ 1, 0, 1, 0,
1 },{ 0, 1, 0, 1, 0 },{ 1, 0, 1, 0, 0 },{ 1, 1, 0, 0, 0 },};
private static final int[][] matrix = { { 0, 1, 0, 0, 0, 0, 0 },{ 1, 0,
1, 0, 0, 0, 0 },{ 0, 1, 0, 1, 1, 0, 0 },{ 0, 0, 1, 0, 1, 1, 1 },{ 0, 0, 1, 1, 0
, 1, 0 },{ 0, 0, 0, 1, 1, 0, 0 },{ 0, 0, 0, 1, 0, 0, 0 },};
private static final int no_vertices = matrix[0].length;
private static final boolean arr[] = new boolean[no_vertices];
private static void printEnabledVertices(String s)
{
for (int i = 0; i < no_vertices; i++)
{
if (arr[i] == true)
{
System.out.print(" " + name_vertex[i]);
}
}
System.out.println("");
pickMinimum();
}
private static void checkVertexCover()
{
int count = 0;
for (int i = 0; i < no_vertices; i++)
{
for (int j = 0; j < i; j++)
{
if (matrix[i][j] == 1)
{
if (arr[i] || arr[j])
{
count++;
}
else
{
return;
}
}
}
}
if (count > 0)
{
printEnabledVertices(null);
}
}
private static void calcVertexCover(int index)
{
if (index == (-1))
{
checkVertexCover();
}
else
{
arr[index] = false;
calcVertexCover(index - 1);
arr[index] = true;
calcVertexCover(index - 1);
}
}
public static void main(String args[])
{
System.out.println("\n\n Vertex Covers Are");
System.out.println("-----------------------");
calcVertexCover(no_vertices - 1);
printMinimum();
}
private static int min_cover_vertices = no_vertices;
private static Set<String> min_cover = new HashSet<String>();
private static String getVertexString()
{
StringBuffer s = new StringBuffer();
for (int i = 0; i < no_vertices; i++)
{
if (arr[i] == true)
{
s.append(" " + name_vertex[i]);
}
}
return s.toString();
}
private static void pickMinimum()
{
int count = 0;
for (int i = 0; i < no_vertices; i++)
{
if (arr[i] == true)
{
count++;
}
}
if (count > 0)
{
if (min_cover_vertices == count)
{
min_cover.add(getVertexString());
}
else if (min_cover_vertices > count)
{
min_cover_vertices = count;
min_cover.clear();
min_cover.add(getVertexString());
}
}
}
private static void printMinimum()
{
if (min_cover.size() > 0)
{
System.out.println("\n\n Minimum Covers Are");
System.out.println("-----------------------");
for (String s : min_cover)
{
System.out.println(s);
}
}
}
}

You might also like