1. 程式人生 > >判斷一個無向圖是否為二分圖

判斷一個無向圖是否為二分圖

要求:先設計演算法,然後用程式實現。程式可允許輸入一個無向圖,然後自動判斷是否為二分圖

注:一個圖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)

如果有改進的地方,歡迎提出來,謝謝~