刷题笔记26——图论二分图判定

世界上的事情,最忌讳的就是个十全十美,你看那天上的月亮,一旦圆满了,马上就要亏厌;树上的果子,一旦熟透了,马上就要坠落。凡事总要稍留欠缺,才能持恒。 ------莫言

  • visited数组是在如果有环的情况下,防止在图中一直绕圈设置的,类似于剪枝操作,走过了就没必要再走一遍

  • path是在探索过程中,记录此次的遍历路径,从而判断是否有环的

  • 如果是判断的话,visited是无法判断的,path是可以判断的

  • 二分图的题背会板子即可

785. 判断二分图:如果没访问就染色,访问过就判断染色是否匹配

java 复制代码
class Solution {
    boolean[] visited;
    int[] color;
    boolean isB = true;
    public boolean isBipartite(int[][] graph) {
        int sz = graph.length;
        color = new int[sz];
        visited =new boolean[sz];
        for(int i=0;i<sz;i++){
            traverse(graph,i,1);
        }
        return isB;
    }

    void traverse(int[][] graph, int n, int col){
        if(visited[n]) return;
        visited[n] = true;
        color[n] = col;
        for(int node:graph[n]){
            if(visited[node]){
                if(color[node]!=(1-col)){
                    isB = false;
                }
            }else{
                traverse(graph,node,1-col);
            }
        }
    }
}

886. 可能的二分法:有边的话就需要将两个节点分开,用二分图的思路

java 复制代码
class Solution {
    // 遍历构图二分图
    boolean[] visited;
    int[] color;
    boolean isBi = true;
    public boolean possibleBipartition(int n, int[][] dislikes) {
        // 构造的是无向图
        visited = new boolean[n];
        color = new int[n];
        List<Integer>[] graph = generateGraph(n,dislikes);
        for(int i=0;i<n;i++){
            traverse(graph,i,1);
        }
        return isBi;
    }

    void traverse(List<Integer>[] graph,int n,int number){
         if(visited[n]) return;
         visited[n] = true;
         color[n] = number;
         for(int node:graph[n]){
             if(visited[node]){
                 if(color[node]!=1-number){
                     isBi = false;
                 }
             }
             else{
                 traverse(graph,node,1-number);
             }
         }
    }

    List<Integer>[] generateGraph(int n, int[][] dislikes){
        List<Integer>[] graph = new LinkedList[n];
        for(int i=0;i<n;i++){
            graph[i] = new LinkedList();
        }
        for(int i=0;i<dislikes.length;i++){
            graph[dislikes[i][0]-1].add(dislikes[i][1]-1);
            graph[dislikes[i][1]-1].add(dislikes[i][0]-1);
        }
        return graph;
    }
}
相关推荐
ps酷教程3 小时前
Jackson 解决没有无参构造函数的反序列化问题
java
NiceCloud喜云3 小时前
Opus 4.8 的 Effort Control 怎么选:Low 到 Max 五档策略
android·java·大数据·前端·c++·python·spring
小羊在睡觉3 小时前
力扣84. 柱状图中最大的矩形
后端·算法·leetcode·golang·go
3DVisionary3 小时前
蓝光三维扫描:医疗制造的精度焦虑怎么解
人工智能·算法·制造·蓝光三维扫描·医疗制造·三维检测·义齿检测
好评笔记3 小时前
机器学习面试八股——常用损失函数
人工智能·深度学习·算法·机器学习·校招
weixin_468466853 小时前
全局与局部注意力机制新手实战指南
人工智能·python·深度学习·算法·自然语言处理·transformer·注意力机制
sheeta19984 小时前
LeetCode 每日一题笔记 日期:2026.05.29 题目:3300. 最小元素
笔记·leetcode
_日拱一卒4 小时前
LeetCode:994腐烂的橘子
java·数据结构·算法·leetcode·深度优先
隔窗听雨眠4 小时前
Nginx网关响应慢排查手记
java·服务器·nginx
中屹指纹浏览器4 小时前
2026指纹浏览器代理链路适配原理与多线路集群调度方案
经验分享·笔记