当前位置: 首页 > news >正文

力扣labuladong——一刷day79

提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档

文章目录

  • 前言
  • 一、力扣785. 判断二分图
  • 二、力扣886. 可能的二分法


前言


给你一幅「图」,请你用两种颜色将图中的所有顶点着色,且使得任意一条边的两个端点的颜色都不相同,你能做到吗? 这就是图的「双色问题」,其实这个问题就等同于二分图的判定问题,如果你能够成功地将图染色,那么这幅图就是一幅二分图,反之则不是:

一、力扣785. 判断二分图

class Solution {boolean ok = true;boolean[] visited;boolean[] color;public boolean isBipartite(int[][] graph) {int n = graph.length;visited = new boolean[n];color = new boolean[n];for(int i = 0; i < n; i ++){if(!visited[i]){traverse(graph, i);}}return ok;}public void traverse(int[][] graph, int v){if(!ok){return;}visited[v] = true;for(int e : graph[v]){if(!visited[e]){color[e] = !color[v];traverse(graph,e);}else{if(color[e] == color[v]){ok = false;return;}}}}
}

二、力扣886. 可能的二分法

class Solution {boolean ok = true;boolean[] visited;boolean[] color;public boolean possibleBipartition(int n, int[][] dislikes) {visited = new boolean[n];color = new boolean[n];List<Integer>[] graph = builderGraph(dislikes, n);for(int i = 0; i < n; i ++){if(!visited[i]){BFS(graph, i);}}return ok;}public List<Integer>[] builderGraph(int[][] dislikes,int n){List<Integer>[] graph = new LinkedList[n];for(int i = 0; i < n ; i ++){graph[i] = new LinkedList<>();}for(int[] arr : dislikes){int to = arr[0]-1;int from = arr[1]-1;graph[to].add(from);graph[from].add(to);}return graph;}public void BFS(List<Integer>[] graph, int v){if(!ok){return;}Deque<Integer> deq = new LinkedList<>();deq.offerLast(v);visited[v] = true;while(!deq.isEmpty()){int cur = deq.pollFirst();for(int e : graph[cur]){if(!visited[e]){visited[e] = true;color[e] = !color[cur];deq.offerLast(e);}else{if(color[e] == color[cur]){ok = false;return;}}}}}
}
http://www.lryc.cn/news/266385.html

相关文章:

  • 【数据结构入门精讲 | 第十篇】考研408排序算法专项练习(二)
  • 【ES实战】Elasticsearch6开始的CCR
  • Deployment Pay
  • MySQL创建member表失败
  • 使用minio实现大文件断点续传
  • 插入排序之C++实现
  • Tomcat日志乱码了怎么处理?
  • [node] Node.js的路由
  • 网络编程第三天作业
  • AIGC:大语言模型LLM的幻觉问题
  • 【C语言刷题每日一题#牛客网BC68】——X形图案
  • 阻断血缘关系以及checkpoint文件清理
  • PHP代码审计之反序列化攻击链CVE-2019-6340漏洞研究
  • PyTorch之线性回归
  • SSTI模板注入基础(Flask+Jinja2)
  • React网页转换为pdf并下载|使用jspdf html2canvas
  • EASYEXCEL导出表格(有标题、单元格合并)
  • pytest 断言异常
  • 听GPT 讲Rust源代码--src/tools(22)
  • OD Linux发行版本
  • 华为端口隔离简单使用方法同vlan下控制个别电脑不给互通
  • DaVinci各版本安装指南
  • 【黑马甄选离线数仓day10_会员主题域开发_DWS和ADS层】
  • OD 完美走位
  • SpringSecurity6 | 失败后的跳转
  • MySQL数据库增删改查
  • Altium Designer(AD24)新工程复用设计文件图文教程及视频演示
  • Python遥感影像深度学习指南(1)-使用卷积神经网络(CNN、U-Net)和 FastAI进行简单云层检测
  • Hive-DML详解(超详细)
  • PHP实现可示化代码