图论中,有很多算法可以实现图的验证,最基本的两个算法是深度优先搜索和广度优先搜索。还有其它高级算法也可以实现类似的功能,但是它们都是基于这两个基础算法之上的。例如:A, IDA, Kosaraju algorithm 和Tarjan algorithm 等等。我会在之后的博客中加以介绍。
在二分图的验证中主要有两个主要函数块,一个是邻接矩阵的建立,另一个则是对顶点颜色的划分和存储。使用DFS算法则是主要对边进行的操作,在这里不多做论述。
在第一个函数中创建一个颜色数组来存储分配给所有种类的颜色。 顶点数用作此数组中的索引。 colorArr [i]的值’-1’用于指示没有颜色被分配给顶点’i’。 值1用于指示第一种颜色被分配,值0指示第二种颜色被分配。
在下一个函数中,它创建了一个邻接矩阵,基于图论的数学字段,二分图(或bigraph)是一个图,其顶点可以分为两个不相交的集合,使得每个边缘将一个顶点连接到一个 并且是每个独立的集合(Tannenbaum&Arnold,1998)。 同等地,二分图是不包含任何奇长度循环的图。
以下是实现该算法的JAVA代码:
// Java program to find out whether a given graph is Bipartite or not
import java.util.*;
import java.lang.*;
import java.io.*;
class Bipartite
{
private int numberOfVertices;
private Queue<Integer> queue;
public BipartiteBfs(int numberOfVertices)
{
this.numberOfVertices = numberOfVertices;
queue = new LinkedList<Integer>();
}
// This function returns true if graph G[V][V] is Bipartite, else false
public boolean isBipartite(int adjacencyMatrix[][], int src)//adjacencyMatrix=int G[][V]
{
int colorArr[] = new int[V];
for (int i=0; i<numberOfVertices; ++i)
colorArr[i] = -1;
// Assign first color to source
colorArr[src] = 1;
// Create a queue (FIFO) of vertex numbers and enqueue
// source vertex for BFS traversal
LinkedList<Integer>queue = new LinkedList<Integer>();//queue=q
queue.add(src);
int element, neighbour;
while (!queue.isEmpty())
{
element = queue.remove();
neighbour = 1;
while (neighbour <= numberOfVertices)
{
if (adjacencyMatrix[element][neighbour] == 1 && colored[element]== colored[neighbour])
{
return false;
}
if (adjacencyMatrix[element][neighbour] == 1 && colored[neighbour]== -1)
{
colored[neighbour] = (1 - colored[element]);
queue.add(neighbour);
}
neighbour++;
}
}
return true;
}
public static void main(String... arg)
{
int number_of_nodes, source;
Scanner scanner = null;
try
{
System.out.println("Enter the number of nodes in the graph");
scanner = new Scanner(System.in);
number_of_nodes = scanner.nextInt();
int adjacency_matrix[][] = new int[number_of_nodes + 1][number_of_nodes + 1];
System.out.println("Enter the adjacency matrix");
for (int i = 1; i <= number_of_nodes; i++)
{
for (int j = 1; j <= number_of_nodes; j++)
{
adjacency_matrix[i][j] = scanner.nextInt();
}
}
for (int i = 1; i <= number_of_nodes; i++)
{
for (int j = 1; j <= number_of_nodes; j++)
{
if(adjacency_matrix[i][j] == 1 && adjacency_matrix[j][i] == 0)
{
adjacency_matrix[j][i] = 1;
}
}
}
System.out.println("Enter the source for the graph");
source = scanner.nextInt();
BipartiteBfs bipartiteBfs = new BipartiteBfs(number_of_nodes);
if (bipartiteBfs.isBipartite(adjacency_matrix, source))
{
System.out.println("The given graph is bipartite");
} else
{
System.out.println("The given graph is not bipartite");
}
} catch (InputMismatchException inputMismatch)
{
System.out.println("Wrong Input format");
}
scanner.close();
}
}