算法题 判断二分图

判断二分图

问题描述

存在一个无向图,图中有 n 个节点,编号从 0n - 1。给你一个二维数组 graph 表示图的邻接表,其中 graph[u] 是一个节点数组,表示与节点 u 相邻的节点。

如果可以将图中节点分为两组,使得每条边的两个节点分别属于不同组,则称这个图是二分图

请你判断给定的图是否是二分图。如果是,返回 true;否则,返回 false

示例

输入: graph = [[1,2,3],[0,2],[0,1,3],[0,2]]
输出: false
解释: 节点不能分成两组,使得每条边的两个节点在不同组。
因为存在奇数长度的环(三角形0-1-2-0)。

输入: graph = [[1,3],[0,2],[1,3],[0,2]]
输出: true
解释: 可以将节点分成两组: {0, 2} 和 {1, 3}。

算法思路

经典的图着色问题,可以用深度优先搜索(DFS)广度优先搜索(BFS) 解决。

二分图

  1. 着色:可以用两种颜色对图进行着色,使得相邻节点颜色不同
  2. :图中不存在奇数长度的环(奇环)
  3. 等价:图是二分图 = 图中所有环的长度都是偶数

方法

  • 图着色:为每个节点分配颜色(0或1),相邻节点必须颜色不同
  • 冲突检测:如果发现相邻节点颜色相同,则不是二分图
  • 连通分量:图可能不连通,需要检查所有连通分量

代码实现

方法一:DFS

class Solution {
    /**
     * 使用DFS判断图是否为二分图
     * 
     * @param graph 邻接表表示的无向图
     * @return true表示是二分图,false表示不是
     */
    public boolean isBipartite(int[][] graph) {
        int n = graph.length;
        // color[i] 表示节点i的颜色,-1表示未着色,0和1表示两种颜色
        int[] color = new int[n];
        Arrays.fill(color, -1);
        
        // 遍历所有节点,处理可能的多个连通分量
        for (int i = 0; i < n; i++) {
            // 如果节点未着色,从该节点开始DFS着色
            if (color[i] == -1) {
                if (!dfs(graph, color, i, 0)) {
                    return false;
                }
            }
        }
        
        return true;
    }
    
    /**
     * DFS着色函数
     * 
     * @param graph 邻接表
     * @param color 颜色数组
     * @param node  当前节点
     * @param c     当前要着的颜色
     * @return true表示着色成功,false表示发现冲突
     */
    private boolean dfs(int[][] graph, int[] color, int node, int c) {
        // 为当前节点着色
        color[node] = c;
        
        // 遍历所有相邻节点
        for (int neighbor : graph[node]) {
            if (color[neighbor] == -1) {
                // 相邻节点未着色,递归着色为相反颜色
                if (!dfs(graph, color, neighbor, 1 - c)) {
                    return false;
                }
            } else if (color[neighbor] == c) {
                // 相邻节点已着色且颜色相同,发现冲突
                return false;
            }
            // 如果相邻节点颜色不同(color[neighbor] == 1 - c),继续检查
        }
        
        return true;
    }
}

方法二:BFS

import java.util.*;

class Solution {
    /**
     * 使用BFS判断图是否为二分图
     * 
     * @param graph 邻接表表示的无向图
     * @return true表示是二分图,false表示不是
     */
    public boolean isBipartite(int[][] graph) {
        int n = graph.length;
        int[] color = new int[n];
        Arrays.fill(color, -1);
        
        // 遍历所有节点
        for (int i = 0; i < n; i++) {
            if (color[i] == -1) {
                if (!bfs(graph, color, i)) {
                    return false;
                }
            }
        }
        
        return true;
    }
    
    /**
     * BFS着色函数
     * 
     * @param graph 邻接表
     * @param color 颜色数组
     * @param start 起始节点
     * @return true表示着色成功,false表示发现冲突
     */
    private boolean bfs(int[][] graph, int[] color, int start) {
        Queue<Integer> queue = new LinkedList<>();
        queue.offer(start);
        color[start] = 0; // 起始节点着色为0
        
        while (!queue.isEmpty()) {
            int node = queue.poll();
            int currentColor = color[node];
            
            // 遍历相邻节点
            for (int neighbor : graph[node]) {
                if (color[neighbor] == -1) {
                    // 未着色,着相反颜色
                    color[neighbor] = 1 - currentColor;
                    queue.offer(neighbor);
                } else if (color[neighbor] == currentColor) {
                    // 颜色冲突
                    return false;
                }
            }
        }
        
        return true;
    }
}

方法三:并查集

class Solution {
    /**
     * 使用并查集判断二分图
     * 核心思想:每个节点u和它的所有邻居v应该在不同的集合中
     * 将u的所有邻居合并到同一个集合,然后检查u是否与该集合连通
     */
    public boolean isBipartite(int[][] graph) {
        int n = graph.length;
        UnionFind uf = new UnionFind(n);
        
        // 遍历每个节点
        for (int u = 0; u < n; u++) {
            int[] neighbors = graph[u];
            if (neighbors.length == 0) continue;
            
            // 将u的所有邻居合并到同一个集合
            int firstNeighbor = neighbors[0];
            for (int i = 1; i < neighbors.length; i++) {
                uf.union(firstNeighbor, neighbors[i]);
            }
            
            // 检查u是否与邻居集合连通(如果是,则不是二分图)
            if (uf.isConnected(u, firstNeighbor)) {
                return false;
            }
        }
        
        return true;
    }
    
    /**
     * 并查集实现
     */
    class UnionFind {
        private int[] parent;
        private int[] rank;
        
        public UnionFind(int n) {
            parent = new int[n];
            rank = new int[n];
            for (int i = 0; i < n; i++) {
                parent[i] = i;
                rank[i] = 0;
            }
        }
        
        public int find(int x) {
            if (parent[x] != x) {
                parent[x] = find(parent[x]); // 路径压缩
            }
            return parent[x];
        }
        
        public void union(int x, int y) {
            int rootX = find(x);
            int rootY = find(y);
            if (rootX != rootY) {
                // 按秩合并
                if (rank[rootX] < rank[rootY]) {
                    parent[rootX] = rootY;
                } else if (rank[rootX] > rank[rootY]) {
                    parent[rootY] = rootX;
                } else {
                    parent[rootY] = rootX;
                    rank[rootX]++;
                }
            }
        }
        
        public boolean isConnected(int x, int y) {
            return find(x) == find(y);
        }
    }
}

算法分析

  • 时间复杂度

    • DFS/BFS:O(V + E),V是节点数,E是边数
    • 并查集:O(E × α(V)),α为常数
  • 空间复杂度

    • DFS:O(V) - 递归栈空间
    • BFS:O(V) - 队列空间
    • 并查集:O(V) - parent和rank数组

算法过程

1:graph = [[1,3],[0,2],[1,3],[0,2]](二分图)

DFS过程

  • 从节点0开始,着色为0
  • 节点1和3着色为1
  • 从节点1,节点2着色为0
  • 从节点3,检查节点2已着色为0(与节点3的1不同)
  • 所有节点着色成功,返回true

着色结果

  • 组0:{0, 2}
  • 组1:{1, 3}

2:graph = [[1,2,3],[0,2],[0,1,3],[0,2]](非二分图)

DFS过程

  • 从节点0开始,着色为0
  • 节点1、2、3着色为1
  • 从节点1,检查节点2已着色为1(与节点1相同)
  • 发现冲突,返回false

冲突原因:存在三角形环0-1-2-0(奇数长度环)

测试用例

public static void main(String[] args) {
    Solution solution = new Solution();
    
    // 测试用例1:标准二分图
    int[][] graph1 = {{1,3},{0,2},{1,3},{0,2}};
    System.out.println("Test 1: " + solution.isBipartite(graph1)); // true
    
    // 测试用例2:非二分图(奇环)
    int[][] graph2 = {{1,2,3},{0,2},{0,1,3},{0,2}};
    System.out.println("Test 2: " + solution.isBipartite(graph2)); // false
    
    // 测试用例3:单个节点
    int[][] graph3 = {{}};
    System.out.println("Test 3: " + solution.isBipartite(graph3)); // true
    
    // 测试用例4:两个节点一条边
    int[][] graph4 = {{1},{0}};
    System.out.println("Test 4: " + solution.isBipartite(graph4)); // true
    
    // 测试用例5:三个节点形成三角形
    int[][] graph5 = {{1,2},{0,2},{0,1}};
    System.out.println("Test 5: " + solution.isBipartite(graph5)); // false
    
    // 测试用例6:四个节点形成正方形
    int[][] graph6 = {{1,3},{0,2},{1,3},{0,2}};
    System.out.println("Test 6: " + solution.isBipartite(graph6)); // true
    
    // 测试用例7:不连通图(多个连通分量)
    int[][] graph7 = {{1},{0},{3},{2}};
    System.out.println("Test 7: " + solution.isBipartite(graph7)); // true
    
    // 测试用例8:不连通图包含奇环
    int[][] graph8 = {{1,2},{0,2},{0,1},{4},{3}};
    System.out.println("Test 8: " + solution.isBipartite(graph8)); // false
    
    // 测试用例9:空图
    int[][] graph9 = {};
    System.out.println("Test 9: " + solution.isBipartite(graph9)); // true
    
    // 测试用例10:星型图
    int[][] graph10 = {{1,2,3,4},{0},{0},{0},{0}};
    System.out.println("Test 10: " + solution.isBipartite(graph10)); // true
}

关键点

  1. 二分图

    • 节点可分为两个互斥集合
    • 每条边的两个端点属于不同集合
  2. 着色策略

    • 使用两种颜色(0和1)
    • 相邻节点必须颜色不同
    • 颜色数组初始值为-1表示未访问
  3. 连通分量

    • 图可能不连通,需要遍历所有节点
    • 每个连通分量都要是二分图
  4. 冲突检测

    • 发现相邻节点同色立即返回false
    • 不需要继续处理其他部分
    • 邻接表形式,graph[u]包含u的所有邻居
    • 无向图,如果u在graph[v]中,则v也在graph[u]中

常见问题

  1. 为什么奇数长度的环会导致不是二分图?

    • 奇环中,从任意节点开始着色,最终会回到起始节点且颜色冲突
    • 偶环可以成功着色,奇环不行
  2. 并查集?

    • 每个节点u的邻居应该在同一集合中
    • u本身不应该与该集合连通
    • 如果连通,说明存在奇环
### C++ 实现 LeetCode 785 题判断二分图的解法 以下是基于 DFS 的方法来解决该问题的完整代码实现: ```cpp class Solution { public: bool isBipartite(vector<vector<int>>& graph) { int n = graph.size(); vector<int> color(n, -1); // 初始化颜色数组,-1 表示未着色 for (int i = 0; i < n; ++i) { if (color[i] == -1 && !dfs(i, 0, color, graph)) { // 如果节点未被访问过且无法成功染色,则返回 false return false; } } return true; // 所有连通部分均能成功染色 } private: bool dfs(int node, int c, vector<int>& color, const vector<vector<int>>& graph) { color[node] = c; // 当前节点染色为 c for (auto& neighbor : graph[node]) { // 遍历当前节点的所有邻居节点 if (color[neighbor] != -1) { // 如果邻居已经染色 if (color[neighbor] == color[node]) { // 判断是否与当前节点颜色相同 return false; // 若相同,则不是二分图 } } else { // 如果邻居尚未染色 if (!dfs(neighbor, c ^ 1, color, graph)) { // 对邻居进行相反的颜色染色并继续深搜 return false; // 如果失败则返回 false } } } return true; // 成功完成染色 } }; ``` #### 解析 上述代码通过深度优先搜索(DFS)的方式实现了对无向图是否为二分图的判定。核心逻辑在于利用两个颜色 `c` 和 `c ^ 1` 来交替标记相邻节点的颜色[^2]。 1. **初始化**: 使用一个大小为 `n` 的 `color` 数组表示每个节点的颜色状态,初始值设为 `-1`,即未染色。 2. **遍历所有节点**: 对于每一个未染色的节点调用 `dfs` 函数尝试对其进行染色操作。 3. **DFS 过程**: - 将当前节点设置为其指定的颜色 `c`。 - 遍历其邻接表中的所有邻居节点: - 如果邻居已经被染色,检查它是否与当前节点颜色冲突。如果有冲突,则说明这不是一个二分图。 - 如果邻居还未被染色,则对其执行递归调用,并赋予与其父节点不同的颜色 (`c ^ 1`)。 4. **最终结果**: 只要有一个子图无法满足二分条件,整个函数就会立即返回 `false`;否则,在全部节点都处理完毕后返回 `true`。 此算法的时间复杂度为 O(V + E),其中 V 是顶点数,E 是边的数量[^4]。 --- ###
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值