785. 判断二分图
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/81d1ff699584a30c2dfae5ef6e6bffbf.png)
class Solution {
public:
vector<int> father;
void init(int N) {
father = vector<int>(N);
for(int ii = 0; ii < N; ii++) father[ii] = ii;
}
int find(int x) {
if(x != father[x]) father[x] = find(father[x]);
return father[x];
}
void unionTwo(int x, int y) {
if(father[x] != father[y]) {
father[find(x)] = find(y);
}
}
bool isConnect(int x, int y) {
return father[x] == father[y];
}
bool isBipartite(vector<vector<int>>& graph) {
init(graph.size());
for(int ii = 0; ii < graph.size(); ii++) {
for(auto jj : graph[ii]) {
if(isConnect(ii, jj)) return false;
unionTwo(graph[ii][0], jj);
}
}
return true;
}
};
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/4457d7d29385a77eaeb4698723296934.png)
class Solution {
public:
bool isBipartite(vector<vector<int>>& graph) {
vector<int> colors(graph.size(), 0);
queue<int> Q;
for(int ii = 0; ii < graph.size(); ii++) {
if(!colors[ii]) {
colors[ii] = 1;
Q.push(ii);
}
while(!Q.empty()) {
int ind = Q.front();
Q.pop();
for(auto jj : graph[ind]) {
if(colors[jj] == colors[ind]) return false;
if(!colors[jj]) {
colors[jj] = -colors[ind];
Q.push(jj);
}
}
}
}
return true;
}
};
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/ea98c9f240fc5da9dfa5f797192a3d12.png)
class Solution {
public:
bool dfs(vector<vector<int>>& graph, vector<int>& colors, int color, int ind) {
colors[ind] = color;
for(auto num : graph[ind]) {
if(colors[num] == color) return false;
if(!colors[num] && !dfs(graph, colors, -color, num)) return false;
}
return true;
}
bool isBipartite(vector<vector<int>>& graph) {
vector<int> colors(graph.size(), 0);
for(int ii = 0; ii < graph.size(); ii++) {
if(!colors[ii] && !dfs(graph, colors, 1, ii)) return false;
}
return true;
}
};