二分图判定

二分图判定

http://www.nowcoder.com/questionTerminal/f4b8d0481c7b4278b9b406b636e3c7db

import java.util.*;
public class Main{
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int N = sc.nextInt();
        int M = sc.nextInt();
        boolean[][] graph = new boolean[N + 1][N + 1];//邻接边置为true
        int[] color = new int[N + 1];//未访问0,白色1,黑色-1
        for(int i = 0; i < M; ++i){
            int a = sc.nextInt();
            int b = sc.nextInt();
            graph[a][b] = true;
            graph[b][a] = true;
        }
        List<Integer> v = new LinkedList<>();//增删操作比较多(也可以直接用队列)
        for(int i = 1; i <= N; ++i){
            if(color[i] != 0) continue;//涂过色的点已经被之前的连通分量访问了
            else color[i] = 1;//给当前连通分量的第1个点涂白色
            v.add(i);
            while(!v.isEmpty()){//广度优先遍历
                int p = v.get(0);
                v.remove(0);
                for(int j = 1; j <= N; ++j){
                    if(graph[p][j] && color[j] == 0) {//邻接的点,若未被访问过,
                        v.add(j);//就入队,
                        color[j] = -color[p];//并涂上相反颜色
                    }else if(graph[p][j] && color[j] == color[p]){//邻接的点同色
                        System.out.println("No");
                        return;
                    }
                }
            }
        }
        System.out.println("Yes");
    }
}
全部评论

相关推荐

2 收藏 评论
分享
牛客网
牛客企业服务