判断一个无向图是否为二分图

要求:先设计算法,然后用程序实现。程序可允许输入一个无向图,然后自动判断是否为二分图

注:一个图G=(V,E)是二分图如果存在V的一个划分V= XY,其中XY=空集。


话不多说,直接上代码


package test;
import java.util.Scanner;

public class graph {  
  
	public static boolean find(int x,int [] arr){
		for(int i = 0;i<arr.length;i++){
			if(x == arr[i])
				return true;
		}
		return false;
	}
    //无向图的邻接表  
    public static void main(String[] args) {  
          
        Scanner scan = new Scanner(System.in);  
        int V = scan.nextInt();//顶点的个数  
        int E = scan.nextInt();//边的条数  
          
        Node adj[] = new Node[V];  
        for(int i=0;i<V;i++){  
            adj[i] = null;  
        }  
          
        for(int i=0;i<E;i++){  
            String input = scan.next();  
            int x = Integer.parseInt(input.substring(1, 2));  
            int y = Integer.parseInt(input.substring(3, 4));  
            adj[y] = new Node(x,adj[y]);  
            adj[x] = new Node(y,adj[x]);  
        }  
        
        int one[] = new int[V];
        int oth[] = new int[V];
        int onee=0,othh=0;
        for(int i =0;i< V;i++){
        	one[i] = -1;
        	oth[i] = -1;
        }
        for(int i=0;i<V;i++){
        	if(find(i,oth)){
        		for(Node temp=adj[i];temp!=null;temp=temp.next){  
        			if(!find(temp.val,oth)&&!find(temp.val,one)){
        				one[onee++] = temp.val;
        			}else if(find(temp.val,oth)){
        				System.out.println("不是二分图!!!");
        				return;
        			}
        		}
        	}
        	else{
        		if(!find(i,one)){
        			one[onee++] = i;
        		}
        		for(Node temp=adj[i];temp!=null;temp=temp.next){  
        			if(!find(temp.val,oth)&&!find(temp.val,one)){
        				oth[othh++] = temp.val;
        			}else if(find(temp.val,one)){
        				System.out.println("不是二分图!!!");
        				return;
        			}
        	//		System.out.print(temp.val+" ");  
        		} 
        	}
     //       System.out.println();  
        }  
        System.out.println("是二分图~~~~~~~~");
        System.out.println("第一部分:");
        for(int i =0;i< V;i++){
        	System.out.print(one[i]+" ");
        }
        System.out.println();
        System.out.println("第二部分:");
        for(int i =0;i< V;i++){
        	System.out.print(oth[i]+" ");
        }
    }  
static class Node{  
    int val;  
    Node next;  
    public Node(int val,Node next){  
        this.val = val;  
        this.next = next;  
    }  
}  
}  

测试1:

6

8

(0,3)

(0,4)

(0,5)

(1,3)

(1,4)

(1,5)

(2,3)

(2,5)

 

测试2

4

3

(0,2)

(0,3)

(2,3)

如果有改进的地方,欢迎提出来,谢谢~

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值