enumColor{kWhite,kRed,kGreen};classSolution{public:boolpossibleBipartition(intn,vector<vector<int>>&dislikes){vector<vector<int>>graph(n+1);vector<Color>colors(n+1,Color::kWhite);for(constvector<int>&d:dislikes){constintu=d[0];constintv=d[1];graph[u].push_back(v);graph[v].push_back(u);}// Reduce to 785. Is Graph Bipartite?for(inti=1;i<=n;++i)if(colors[i]==Color::kWhite&&!isValidColor(graph,i,colors,Color::kRed))returnfalse;returntrue;}private:boolisValidColor(constvector<vector<int>>&graph,intu,vector<Color>&colors,Colorcolor){// The painted color should be same as the `color`if(colors[u]!=Color::kWhite)returncolors[u]==color;colors[u]=color;// Always paint w/ `color`// All children should have valid colorsfor(constintv:graph[u])if(!isValidColor(graph,v,colors,color==Color::kRed?Color::kGreen:Color::kRed))returnfalse;returntrue;}};
enumColor{kWhite,kRed,kGreen}classSolution{publicbooleanpossibleBipartition(intn,int[][]dislikes){List<Integer>[]graph=newList[n+1];Color[]colors=newColor[n+1];Arrays.fill(colors,Color.kWhite);for(inti=1;i<=n;++i)graph[i]=newArrayList<>();for(int[]d:dislikes){finalintu=d[0];finalintv=d[1];graph[u].add(v);graph[v].add(u);}// Reduce to 785. Is Graph Bipartite?for(inti=1;i<=n;++i)if(colors[i]==Color.kWhite&&!isValidColor(graph,i,colors,Color.kRed))returnfalse;returntrue;}privatebooleanisValidColor(List<Integer>[]graph,intu,Color[]colors,Colorcolor){// The painted color should be same as the `color`if(colors[u]!=Color.kWhite)returncolors[u]==color;colors[u]=color;// Always paint w/ `color`// All children should have valid colorsfor(finalintv:graph[u])if(!isValidColor(graph,v,colors,color==Color.kRed?Color.kGreen:Color.kRed))returnfalse;returntrue;}}
fromenumimportEnumclassColor(Enum):kWhite=0kRed=1kGreen=2classSolution:defpossibleBipartition(self,n:int,dislikes:List[List[int]])->bool:graph=[[]for_inrange(n+1)]colors=[Color.kWhite]*(n+1)foru,vindislikes:graph[u].append(v)graph[v].append(u)# Reduce to 785. Is Graph Bipartite?defisValidColor(u:int,color:Color)->bool:# The painted color should be same as the `color`ifcolors[u]!=Color.kWhite:returncolors[u]==colorcolors[u]=color# Always paint w/ `color`# All children should have valid colorschildrenColor=Color.kRedifcolors[u]==Color.kGreenelseColor.kGreenreturnall(isValidColor(v,childrenColor)forvingraph[u])returnall(colors[i]!=Color.kWhiteorisValidColor(i,Color.kRed)foriinrange(1,n+1))