LeetCode 785. 判断二分图
思路
染色问题,很简单,dfs对附近的点走下一个颜色,如果下一个颜色冲突返回false,本个也就直接false。
问题一般出在只对一个点进行dfs,因为是无向环图,所以可能出现子图无法被第一个点访问到的问题,所以要对
所有点进行dfs染色。
代码
class Solution {
public int [] color;
public int [][] graph;
public boolean isBipartite(int[][] graph) {
if(graph.length==0)return false;this.graph=graph;
color=new int[graph.length];
for(int i =0;i<color.length;i++){
color[i]=-1;
}
for(int i =0;i<graph.length;i++){
if(graph[i].length!=0&&color[i]==-1){
for(int k =0;k<graph[i].length;k++){
if(!isOkay(-1,graph[i][k],0))return false;
}
}
}
return true;
}
public boolean isOkay(int from,int to,int nextcolor){
if(color[to]!=nextcolor&&color[to]!=-1){return false;}
if(color[to]!=-1)return true;
color[to]=nextcolor;
nextcolor=(nextcolor+1)%2;
for(int i=0;i<this.graph[to].length;i++){
if(!isOkay(to,graph[to][i],nextcolor)){
return false;
}
}
return true;
}
}