主页有其他数据结构内容(持续更新中)
难度:Medium
代码:
法一:BFS
class Solution {
private:
const int Uncolored = 0;
const int Red = 1;
const int Green = 2;
vector<int> color;
bool valid = true;
void dfs(int node, int targetColor, vector<vector<int>> graph) {
color[node] = targetColor;
for(auto c : graph[node]) {
int nextColor = targetColor == Red ? Green : Red;
if(color[c] == Uncolored) { // 若未涂色,则对该节点进行dfs
dfs(c, nextColor, graph);
if(!valid) {
return;
}
}
else if(nextColor != color[c]) { // 若已涂色并且与正确颜色不符,将valid置为false并退出dfs
valid = false;
return;
}
}
}
public:
bool isBipartite(vector<vector<int>>& graph) {
int num = graph.size();
color.assign(num, Uncolored); // 将所有节点初始化为未涂色状态
// 这里使用for循环是因为所给的图不一定是连通图;对于非连通图,无法通过一次dfs遍历所有节点
for(int i = 0; i < num && valid; i++) { // 此处需要判断valid是否为真,否则直接退出循环返回false
if(color[i] == Uncolored) {
// 当前节点未涂色才进行dfs
// 默认将当前节点涂上红色
dfs(i, Red, graph);
}
}
return valid;
}
};
法二:DFS
class Solution {
private:
const int Uncolored = 0;
const int Red = 1;
const int Green = 2;
vector<int> color;
public:
bool isBipartite(vector<vector<int>>& graph) {
int num = graph.size();
color.assign(num, Uncolored);
for(int i = 0; i < num; i++) {
if(color[i] == Uncolored) { // 只有未涂色节点才进行bfs
queue<int> q;
q.push(i);
color[i] = Red; // 默认给当前节点涂上红色
while(!q.empty()) {
int node = q.front();
q.pop();
int nextColor = color[node] == Red ? Green : Red;
for(auto c : graph[node]) {
if(color[c] == Uncolored) {
color[c] = nextColor;
q.push(c);
}
else if(color[c] != nextColor) {
return false;
}
}
}
}
}
return true;
}
};