其他分享
首页 > 其他分享> > LeetCode 785. Is Graph Bipartite?

LeetCode 785. Is Graph Bipartite?

作者:互联网

Given an undirected graph, return true if and only if it is bipartite.
Recall that a graph is bipartite if we can split it's set of nodes into two independent subsets A and B such that every edge in the graph has one node in A and another node in B.
The graph is given in the following form: graph[i] is a list of indexes j for which the edge between nodes i and j exists.  Each node is an integer between 0 and graph.length - 1.  There are no self edges or parallel edges: graph[i] does not contain i, and it doesn't contain any element twice.

判断二分图,二分图染色的基本做法,DFS加染色

 1 class Solution {
 2 public:
 3     int c=1;
 4     int color[110]={0};
 5     bool isBipartite(vector<vector<int>>& graph) {
 6         for(int i=0; i<graph.size(); i++){
 7             if(color[i]==0){
 8                 if(!DFS(i,c,graph)){
 9                     return false;
10                 }
11             }
12         }
13         return true;
14     }
15     bool DFS(int v, int c,vector<vector<int>>& graph){
16         color[v]=c;
17         for(int i=0; i<graph[v].size(); i++){
18             if(color[graph[v][i]]==c)
19                 return false;
20             if(color[graph[v][i]]==0&&!DFS(graph[v][i],-c,graph))
21                 return false;
22         }
23         return true;
24     }
25 };

 

标签:node,785,int,graph,LeetCode,edges,between,nodes,Bipartite
来源: https://www.cnblogs.com/Scotton-Wild/p/10290423.html