AcWing 860. Judging Bipartite Graph by Coloring Method (Java)_Bipartite Graph_Coloring Method_DFS

Dyeing method to determine the bipartite graph

Original title link

①. Title

Insert picture description here

②. Thinking

Insert picture description here

  • Odd-numbered ring: a ring formed by odd-numbered edges
  • Bipartite graph: If and only if the graph does not contain odd rings, there are no edges inside the two sets
	//DFS
* 染色可以使用12区分不同颜色,用0表示未染色
* 遍历所有点,每次将未染色的点进行dfs, 默认染成1或者2
* 由于某个点染色成功不代表整个图就是二分图,因此只有某个点染色失败才能立刻break/return
*

③. Learning points

二分图_染色法

④. Code implementation

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;

public class Main {
    
    
	/*
	 * 奇数环:由奇数条边形成的一个环
	 * 二分图 当且仅当图中不含奇数环,两个集合内部没有边
	 */
	//DFS
	/*
	 * 染色可以使用1和2区分不同颜色,用0表示未染色
	 * 遍历所有点,每次将未染色的点进行dfs, 默认染成1或者2
	 * 由于某个点染色成功不代表整个图就是二分图,因此只有某个点染色失败才能立刻break/return
	 */
	static int N=200010,n,m,idx;     
	static int[] e=new int[N],ne=new int[N],h=new int[N]; //邻接矩阵存储
	static int[] vi=new int[N];
	
	public static void main(String[] args) throws IOException {
    
    
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		String[] s = br.readLine().split(" ");
		n=Integer.parseInt(s[0]);
		m=Integer.parseInt(s[1]);
		Arrays.fill(h,-1);
		while(m-->0) {
    
    
			s=br.readLine().split(" ");
			int a=Integer.parseInt(s[0]);
			int b=Integer.parseInt(s[1]);
			add(a,b);//无向图 两条边都加入到邻接矩阵
			add(b,a);
		}
		
		boolean flag=true;
		for (int i =1; i <=n; i++) {
    
    
			if(vi[i]==0) {
    
    
				if(!dfs(i,1)) {
    
    
					//出现矛盾
					flag=false;
					break;
				}
			}
		}
		if(flag) {
    
    
			System.out.println("Yes");
		}else {
    
    
			System.out.println("No");
		}
	}
	 static void add(int a,int b) {
    
    
		 e[idx]=b;
		 ne[idx]=h[a];
		 h[a]=idx++;
	 }
	 
	 //dfs(u,c)表示把u号点染色成c颜色,并且判断从u号点开始染其他相连的点是否染成功
	 static boolean dfs(int i,int color) {
    
    
		 vi[i]=color;
		 //给当前节点的子节点全部染成一种颜色
		 for (int j=h[i];j!=-1;j=ne[j]) {
    
    
			int nextNode=e[j];
			if(vi[nextNode]==0) {
    
     //若下个节点为染色,dfs进行递归染不同颜色
				if(!dfs(nextNode,3-color)) {
    
     
					return false;
				}
			}else if(vi[nextNode]==color) {
    
     //若相邻节点颜色相同直接false
				return false;
			}
		}
		 return true;
	 }
	
}

Insert picture description here

Guess you like

Origin blog.csdn.net/weixin_45480785/article/details/114155980