利用二分图没有奇环的性质
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;
}
};