二分图判定

二分图判定 给定一个具有n个顶点的图,要给每个顶点染色,并且要使相邻的顶点颜色不同,问是否最多能用两种颜色进行染色?题目保证没有重环和自环。

/*
用邻接表深度遍历

*/

import java.util.ArrayList;
import java.util.Scanner;

public class Test {
    //图的顶点数,总边数
    static int V, E;
    //存储所有的边,大小为顶点数
    static ArrayList<Integer>[] Edges;
    //存储每个顶点的颜色
    static int[] color;

    public static void main(String[] args) {
        creatGraph();
        //题目未说明给定的是连通图,所有需要把所有顶点判定一遍
        for (int i = 0; i < V; i++) {
            if (color[i] == 0) {
                if (!dfs(i, 1)) {
                    System.out.println("No");
                    return;
                }
            }
        }
        System.out.println("Yes");
    }

    static boolean dfs(int v, int c) {
        color[v] = c;
        for (int i = 0; i < Edges[v].size(); i++) {
            if (color[Edges[v].get(i)] == 0) {
                return dfs(Edges[v].get(i), -c);
            } else if (color[Edges[v].get(i)] == c)
                return false;
        }
        return true;
    }

    static void creatGraph() {
        Scanner sc = new Scanner(System.in);
        V = sc.nextInt();
        E = sc.nextInt();
        color = new int[V];
        Edges = new ArrayList[V];
        for (int i = 0; i < V; i++) {
            Edges[i] = new ArrayList<Integer>();
        }
        for (int i = 0; i < E; i++) {
            int u = sc.nextInt();
            int v = sc.nextInt();
            Edges[u].add(v);
            Edges[v].add(u);
        }
    }
}

 
/*
用邻接矩阵深度遍历

*/

import java.util.Arrays;
import java.util.Scanner;

public class Test {
    //图的顶点数,总边数
    static int V, E;
    //存储所有的边,大小为顶点数
    static int[][] Edges;
    //存储每个顶点的颜色
    static int[] color;

    public static void main(String[] args) {
        creatGraph();
        //题目未说明给定的是连通图,所有需要把所有顶点判定一遍
        for (int i = 0; i < V; i++) {
            if (color[i] == 0) {
                if (!dfs(i, 1)) {
                    System.out.println("No");
                    return;
                }
            }
        }
        System.out.println("Yes");
    }

    static boolean dfs(int v, int c) {
        color[v] = c;
        for (int i = 0; i < V; i++) {
            if (Edges[v][i] < Integer.MAX_VALUE) {
                if (color[i] == 0) {
                    return dfs(i, -c);
                } else if (color[i] == c)
                    return false;
            }
        }
        return true;
    }

    static void creatGraph() {
        Scanner sc = new Scanner(System.in);
        V = sc.nextInt();
        E = sc.nextInt();
        color = new int[V];
        Edges = new int[V][V];
        for (int[] i : Edges)
            Arrays.fill(i, Integer.MAX_VALUE);
        for (int i = 0; i < E; i++) {
            int u = sc.nextInt();
            int v = sc.nextInt();
            Edges[u][v] = 1;
            Edges[v][u] = 1;
        }
    }
}

 

posted @ 2018-03-26 20:53  忧伤的小毛驴  阅读(143)  评论(0编辑  收藏  举报