【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;
    }
}

運行結果

在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章