要求:节点是0到n-1,判断能不能染两种色,相邻不一样
思路:子节点如果被染过了且跟要染的不一样则false,如果没染过直接染并遍历
class Solution {
public:
bool ans=true;
void dfs(vector<vector<int>>& graph,vector<int>& v,int i){
if(!ans)return;
int color;
if(v[i]==1)color=2;
else color=1;
for(int j=0;j<graph[i].size();++j){
if(v[graph[i][j]]==0){
v[graph[i][j]]=color;
dfs(graph,v,graph[i][j]);
}
else if(v[graph[i][j]]!=color){
ans=false;
return;
}
}
}
bool isBipartite(vector<vector<int>>& graph) {
int n=graph.size();
vector<int> v(n);
for(int i=0;i<n;++i){
if(v[i]==0){
v[i]=1;
dfs(graph,v,i);
}
}
return ans;
}
};