leetcode785 判断graph是否Bipartite
题目链接:https://leetcode.com/problems/is-graph-bipartite/description/
一个图为Bipartite当且仅当图的节点能分出两个不相交的顶点集合A和B,图中的任意一条边的两个端点不能在同一个集合中。
需要注意的地方:
1.如果一个顶点没有边也是可以的。
2.图可以分离为多个Bipartite图,即是多个满足Bipartite的连通图
解决方法:
BFS:
class Solution {
public boolean isBipartite(int[][] graph) {
if(graph == null || graph.length == 0) return true;
int nodeCount = graph.length;
int[] color = new int[nodeCount];
for(int i = 0;i < nodeCount;i++) color[i] = -1;
for(int i = 0;i < nodeCount;i++){
if(color[i] == -1){
if(!isBipartiteFunc(graph, color, i)) return false;
}
}
return true;
}
public boolean isBipartiteFunc(int[][] graph, int[] color, int src){
Queue<Integer> queue = new LinkedList<>();
color[src] = 0;
queue.add(src);
while(!queue.isEmpty()){
int node = queue.poll();
for(int v : graph[node]){
if(color[v] == -1){
color[v] = 1 - color[node];
queue.offer(v);
}else if(color[v] == color[node]){
return false;
}
}
}
return true;
}
}
DFS:
class Solution {
public boolean isBipartite(int[][] graph) {
int V = graph.length;
if (V <= 1) return true;
Boolean[] colors = new Boolean[V];
for (int i = 0; i < V; i++) if (colors[i] == null && !color (graph, colors, true, i))
return false;
return true;
}
boolean color (int[][] graph, Boolean[] colors, Boolean color, int node) {
if (colors[node] != null) return colors[node] == color;
colors[node] = color;
color = !color;
for (int neighbor : graph[node]) {
if (!color (graph, colors, color, neighbor))
return false;
}
return true;
}
}
如果你对这个算法感兴趣,那么以下链接会有帮助:
geekforgeek的bipartite graph
https://www.geeksforgeeks.org/bipartite-graph/