图论——二分图检测
问题分析
什么是二分图,二分图的定义太过于晦涩,我们可以这么做,如果对于一张图,用黑白两个颜色给顶点染色,要求相邻顶点颜色不同,最终可以完成染色的图就是二分图。
对于上图就是一张二分图,而我们如果加上0-3这条边就不是二分图,染色游戏好像高中组合问题学到过
代码
graph.txt
7 6
0 1
0 2
1 3
2 6
2 3
1 4
二分图检测
//二分图检测,多个连通分量只要一个连通分量不是二分图整体就不是二分图
public class BiPartitionDetection {
private UndirectedGraph graph;
private boolean[] visited;
private int[] colors;
private boolean biPart = true;
public BiPartitionDetection(UndirectedGraph graph){
this.graph = graph;
visited = new boolean[graph.vertexNum()];
colors = new int[graph.vertexNum()];
for(int i=0;i<colors.length;i++){
colors[i] = -1;
}
for(int v=0;v<graph.vertexNum();v++){
if(!visited[v]){
if(!dfs(v,0)){
biPart = false;
break;
}
}
}
}
private boolean dfs(int v,int color){
visited[v] = true;
colors[v] = color;
for(int w:graph.adj(v)) {
if(!visited[w]){
if(!dfs(w,1-color))return false;
}else if(colors[w]==colors[v]){
return false;
}
}
return true;
}
public static void main(String[] args) {
UndirectedGraph graph = new UndirectedGraph("t.txt");
System.out.println(graph);
BiPartitionDetection graphDFS = new BiPartitionDetection(graph);
System.out.println(graphDFS.biPart);
}
}
建图类
public class UndirectedGraph {
private int V;//顶点数
private int E;//边数
private TreeSet<Integer>[] adj;//邻接表,TreeSet数组存储
public UndirectedGraph(String filename){
File file = new File(filename);
try(Scanner scanner = new Scanner(file)){
V = scanner.nextInt();//顶点数
if(V<=0) throw new RuntimeException("顶点个数必须大于0");
adj = new TreeSet[V];
for(int i=0;i<V;i++){
adj[i] = new TreeSet<>();
}
E = scanner.nextInt();//边数
if(E<0) throw new RuntimeException("边数不能为负数");
for(int i=0;i<E;i++){
int a = scanner.nextInt();
validateVertex(a);
int b = scanner.nextInt();
validateVertex(b);
//自环边检测
if(a==b){
throw new RuntimeException("简单图不能包含自环边");
}
//平行边检测
if(adj[a].contains(b)){
throw new RuntimeException("简单图不能包含平行边");
}
adj[a].add(b);
adj[b].add(a);
}
}catch (IOException e){
e.printStackTrace();
}
}
public void validateVertex(int v){
if(v<0||v>=V){
throw new RuntimeException("顶点下标溢出");
}
}
public int vertexNum(){
return V;
}
public int edgeNum(){
return E;
}
public boolean hasEdge(int v,int w){
validateVertex(v);
validateVertex(w);
return adj[v].contains(w);
}
//邻接顶点
public Iterable<Integer> adj(int v){
validateVertex(v);
return adj[v];
}
//度
public int degree(int v){
validateVertex(v);
return adj[v].size();
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(String.format("V = %d,E = %d\n",V,E));
for(int i=0;i<adj.length;i++){
sb.append(i+":");
for (Iterator<Integer> it = adj[i].iterator(); it.hasNext(); ) {
sb.append(it.next()+" ");
}
sb.append("\n");
}
return sb.toString();
}
public static void main(String[] args) {
UndirectedGraph graph = new UndirectedGraph("graph.txt");
System.out.println(graph);
}
}