给定一个无向图graph,当这个图为二分图时返回true。
如果我们能将一个图的节点集合分割成两个独立的子集A和B,并使图中的每一条边的两个节点一个来自A集合,一个来自B集合,我们就将这个图称为二分图。
graph将会以邻接表方式给出,graph[i]表示图中与节点i相连的所有节点。每个节点都是一个在0到graph.length-1之间的整数。这图中没有自环和平行边: graph[i] 中不存在i,并且graph[i]中没有重复的值。
给定一个无向图graph,当这个图为二分图时返回true。
如果我们能将一个图的节点集合分割成两个独立的子集A和B,并使图中的每一条边的两个节点一个来自A集合,一个来自B集合,我们就将这个图称为二分图。
graph将会以邻接表方式给出,graph[i]表示图中与节点i相连的所有节点。每个节点都是一个在0到graph.length-1之间的整数。这图中没有自环和平行边: graph[i] 中不存在i,并且graph[i]中没有重复的值。
示例 1:
输入: [[1,3], [0,2], [1,3], [0,2]]
输出: true
解释:
无向图如下:
0----1
| |
| |
3----2
我们可以将节点分成两组: {0, 2} 和 {1, 3}。
示例 2:
输入: [[1,2,3], [0,2], [0,1,3], [0,2]]
输出: false
解释:
无向图如下:
0----1
| \ |
| \ |
3----2
我们不能将节点分割成两个独立的子集。
注意:
graph 的长度范围为 [1, 100]。
graph[i] 中的元素的范围为 [0, graph.length - 1]。
graph[i] 不会包含 i 或者有重复的值。
图是无向的: 如果j 在 graph[i]里边, 那么 i 也会在 graph[j]里边。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/is-graph-bipartite
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
定义三种状态记做0, -1, 1.其中0表示未访问,-1表示一个集合,1表示另一个集合。
然后遍历该图,为该图染色,染色过程中发现冲突(即本来该元素应该被染为-1,但是发现其之前已经被染为1)则证明该图不为二分图。
使用广度优先遍历是一种很直观的求解,一层一层的染色。遍历过程中对于当前每个节点,把其下一个结点的颜色染成与其不同的颜色,出现冲突返回false。
此外还需要考虑孤立结点的问题,应该所有结点都完成染色才能返回true。
代码如下:
class Solution {
public boolean isBipartite(int[][] graph) {
int N = graph.length;
int[] status = new int[N]; // 0 - 1 1
for(int i = 0; i < N; i++){
if(status[i] == 0){
if(!bfs(i, status, graph)){
return false;
}
}
}
return true;
}
public boolean bfs(int index, int[] status, int[][] graph){
Queue<Integer> queue = new LinkedList<>();
status[index] = 1;
queue.add(index);
while(!queue.isEmpty()){
int cur = queue.remove();
for(int next : graph[cur]){
if(status[next] == status[cur]){
return false;
}else if(status[next] == 0){
status[next] = -1 * status[cur];
queue.add(next);
}
}
}
return true;
}
}
使用深度优先搜索时需要多记录一下当前结点的前一个结点的颜色。
class Solution {
public boolean isBipartite(int[][] graph) {
int N = graph.length;
int[] status = new int[N]; // 0 - 1 1
for(int i = 0; i < N; i++){
if(status[i] == 0){
if(!dfs(i, status, graph, -1)){
return false;
}
}
}
return true;
}
public boolean dfs(int index, int[] status, int[][] graph, int preStatus){
if(status[index] != 0){
return status[index] == -1 * preStatus;
}
status[index] = -1 * preStatus;
for(int next : graph[index]){
if(!dfs(next, status, graph, status[index])){
return false;
}
}
return true;
}
}