LeetCode 785.判断二分图

这篇博客介绍了如何使用广度优先搜索(BFS)和深度优先搜索(DFS)来判断一个图是否是二分图。代码示例中展示了两种方法的实现,通过为节点染色来检查图的二分性。在DFS过程中,当遇到颜色冲突时,会立即返回false,而在BFS过程中,使用队列进行节点染色,并同样检查颜色冲突。
摘要由CSDN通过智能技术生成

主页有其他数据结构内容(持续更新中)

难度: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;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值