785. 判断二分图
Posted hunter01
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了785. 判断二分图相关的知识,希望对你有一定的参考价值。
利用二分图没有奇环的性质
DFS:
class Solution {
private:
static constexpr int UNCOLORED = 0;
static constexpr int RED = 1;
static constexpr int GREEN = 2;
vector<int> color;
bool valid;
public:
void dfs(int node, int c, const vector<vector<int>>& graph) {
color[node] = c;
int cNei = 3-c;
for (int neighbor: graph[node]) {
if (color[neighbor] == UNCOLORED) {
dfs(neighbor, cNei, graph);
if (!valid) {
return;
}
}
else if (color[neighbor] == c) {
valid = false;
return;
}
}
}
bool isBipartite(vector<vector<int>>& graph) {
int n = graph.size();
valid = true;
color.assign(n, UNCOLORED);
for (int i = 0; i < n && valid; ++i) {
if (color[i] == UNCOLORED) {
dfs(i, RED, graph);
}
}
return valid;
}
};
BFS:
class Solution {
public:
bool isBipartite(vector<vector<int>>& graph) {
int n = graph.size();
vector<int> color(n, 0);
for (int i = 0; i < n; ++i) {
if (color[i] == 0) {
queue<int> q;
color[i] = 1;
q.push(i);
while (!q.empty())
{
int top = q.front(); q.pop();
for (auto node : graph[top]) {
if (color[node] == 0) {
color[node] = 3-color[top];
q.push(node);
}
else if (color[node] == color[top]) {
return false;
}
}
}
}
}
return true;
}
};
以上是关于785. 判断二分图的主要内容,如果未能解决你的问题,请参考以下文章
785. 判断二分图——本质上就是图的遍历 dfs或者bfs
785. Is Graph Bipartite?( 判断是否为二分图)