LeetCode 785. Is Graph Bipartite?

Posted scotton-wild

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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 its 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 doesnt 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 };

 

以上是关于LeetCode 785. Is Graph Bipartite?的主要内容,如果未能解决你的问题,请参考以下文章

[leetcode]785. Is Graph Bipartite? [bai'pɑrtait] 判断二分图

LeetCode 785. 判断二分图 | Python

LWC 72: 785. Is Graph Bipartite?

785.Is Graph Bipartite?

785. Is Graph Bipartite?( 判断是否为二分图)

785. Is Graph Bipartite?从两个集合中取点构图