创建两个集合用于保存两组节点
首先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;
}
}