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.
题意:判断是否是二分图,因为一条边两个点集合必定不同,也就是每个连通图中确定了一个点的集合后剩下的点集合必定是确定的,根据这一点用bfs和dfs即可,遇到集合不同时返回false最后返回true
dfs方法:
class Solution {
public:
bool dfs(vector<vector<int>>& graph,vector<int>& color,int u,int co){
if(color[u]!=0) return color[u]==co;
color[u]=co;
for(auto v:graph[u]){
if(!dfs(graph,color,v,-co))return false;
}
return true;
}
bool isBipartite(vector<vector<int>>& graph) {
vector<int> color(graph.size(),0);
for(int i=0;i<graph.size();i++){
if(color[i]==0&&!dfs(graph,color,i,1)) return false;
}
return true;
}
};
bfs方法:
class Solution {
public:
bool bfs(vector<vector<int>>& graph,vector<int>& color,int u,int co){
if(color[u]!=0) return color[u]==co;
queue<int> q;
q.push(u);
color[u]=co;
while(!q.empty()){
int v=q.front();
q.pop();
for(auto x:graph[v]){
if(color[x]==color[v]) return false;
if(color[x]!=0) continue;
color[x]=-color[v];
q.push(x);
}
}
return true;
}
bool isBipartite(vector<vector<int>>& graph) {
vector<int> color(graph.size(),0);
for(int i=0;i<graph.size();i++){
if(color[i]==0&&!bfs(graph,color,i,1)) return false;
}
return true;
}
};
细节:dfs注意访问点时未访问的情况,bfs注意每个点取出来访问出度时遇到已经访问点的情况只要处理false的情况别忘了之后true的情况也要考虑否则下面对color的赋值会覆盖从而产生错误