欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

【leetcode】785. Is Graph Bipartite?

程序员文章站 2022-07-15 17:30:54
...

【leetcode】785. Is Graph Bipartite?
创建两个集合用于保存两组节点
首先0放在集合1,0的邻节点放在集合2
1的邻节点是0和2,0已经在集合1里面了,把2也放到集合1里面去
3的邻节点是0和2,都在集合1里面。
所有节点都放在了集合1和2中,返回true(如果存放过程中出现矛盾返回false)

提交代码

class Solution {
    public boolean isBipartite(int[][] graph) {
    	Set<Integer> g1=new HashSet<>();
    	Set<Integer> g2=new HashSet<>();
    	Queue<Integer> node=new LinkedList<>();
    	
    	while(g1.size()+g2.size()<graph.length) {
    		for(int i=0;i<graph.length;i++) {
    			if(!g1.contains(i)&&!g2.contains(i)) {
    				g1.add(i);
    				node.add(i);
    				break;
    			}
    		}
	    	while(node.size()>0) {
	    		int curNode=node.poll();
	    		if(g1.contains(curNode)) {
	    			for(int i=0;i<graph[curNode].length;i++) {
	    				if(g1.contains(graph[curNode][i]))
	    					return false;
	    				if(!g2.contains(graph[curNode][i])) {
	    					node.offer(graph[curNode][i]);
	    					g2.add(graph[curNode][i]);
	    				}
	    			}
	    		}else {
	    			for(int i=0;i<graph[curNode].length;i++) {
	    				if(g2.contains(graph[curNode][i]))
	    					return false;
	    				if(!g1.contains(graph[curNode][i])) {
	    					node.offer(graph[curNode][i]);
	    					g1.add(graph[curNode][i]);
	    				}
	    			}
	    		}
	    	}
    	}
    	return true;
    }
}

运行结果

【leetcode】785. Is Graph Bipartite?

相关标签: leetcode