微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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 };

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐