思路
- 这个题仍然是注意思路,把二分图转化为给顶点涂色
- 如果每一条边所依附的两个顶点都是不同的颜色 那么他就是一个二分图
- 所以我们的搜索模板 最外层是遍历所有的顶点 如果该顶点尚未上色 就调用辅助函数
- 对于辅助函数 我们先给该顶点上色 然后依次处理和该顶点相邻的所有顶点
- 如果相邻的顶点涂色了 判断是否和当前顶点颜色相反
- 如果没有涂色 那就对该顶点递归调用辅助函数
递归
class Solution {
public boolean isBipartite(int[][] graph) {
int[] color = new int[graph.length];
Arrays.fill(color,-1);
for(int i = 0 ; i < graph.length ; i++){
if(-1 == color[i]){
if(!dfs(graph,color,i,0))
return false;
}
}
return true;
}
private boolean dfs(int[][] graph , int[] colors , int i , int color){
if(colors[i] >= 0){
return colors[i] == color;
}
colors[i] = color;
for(int index : graph[i]){
if(!dfs(graph,colors,index,1-color)){
return false;
}
}
return true;
}
}
迭代~
class Solution {
public boolean isBipartite(int[][] graph) {
int[] color = new int[graph.length];
Arrays.fill(color,-1);
for(int i = 0 ; i < graph.length ; i++){
if(-1 == color[i]){
if(!dfs(graph,color,i,0))
return false;
}
}
return true;
}
private boolean dfs(int[][] graph , int[] colors , int i , int color){
Queue<Integer> queue = new LinkedList();
queue.offer(i);
colors[i] = color;
while(!queue.isEmpty()){
int index = queue.poll();
color = 1 - colors[index];
for(int j : graph[index]){
if(-1 == colors[j]){
colors[j] = color;
queue.offer(j);
}else if (color != colors[j])
return false;
}
}
return true;
}
}