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

Java数据结构与算法(有向无环图)

前言

有向无环图(Directed Graph)是在有向图的基础上,增加无环的检查。

实现原理

使用邻接表表示法实现有向图相对简单明了,步骤也相对简单。

1:首先创建有向图

2.创建顶点

3.顶点间创建边

4.创建边的过程中检查节点是否存在环,每个节点的检查采用递归。

具体代码实现

package test13;import java.util.*;public class DAG {private Map<Vertex, List<Vertex>> adjacencyList;public DAG() {this.adjacencyList = new HashMap<>();}// 添加顶点public void addVertex(String label) {adjacencyList.putIfAbsent(new Vertex(label), new ArrayList<>());}// 添加边并检查是否会形成环public boolean addEdge(String sourceLabel, String destinationLabel) {Vertex source = new Vertex(sourceLabel);Vertex destination = new Vertex(destinationLabel);if (!adjacencyList.containsKey(source) || !adjacencyList.containsKey(destination)) {throw new IllegalArgumentException("顶点不存在");}adjacencyList.get(source).add(destination);// 检查是否形成环if (hasCycle()) {adjacencyList.get(source).remove(destination);return false;}return true;}// 深度优先搜索检查环private boolean hasCycle() {Set<Vertex> visited = new HashSet<>();Set<Vertex> recursionStack = new HashSet<>();for (Vertex vertex : adjacencyList.keySet()) {if (hasCycleUtil(vertex, visited, recursionStack)) {return true;}}return false;}private boolean hasCycleUtil(Vertex vertex, Set<Vertex> visited, Set<Vertex> recursionStack) {if (recursionStack.contains(vertex)) {return true;}if (visited.contains(vertex)) {return false;}visited.add(vertex);recursionStack.add(vertex);for (Vertex neighbor : adjacencyList.get(vertex)) {if (hasCycleUtil(neighbor, visited, recursionStack)) {return true;}}recursionStack.remove(vertex);return false;}// 拓扑排序public List<Vertex> topologicalSort() {Set<Vertex> visited = new HashSet<>();Stack<Vertex> stack = new Stack<>();for (Vertex vertex : adjacencyList.keySet()) {if (!visited.contains(vertex)) {topologicalSortUtil(vertex, visited, stack);}}List<Vertex> sortedList = new ArrayList<>();while (!stack.isEmpty()) {sortedList.add(stack.pop());}return sortedList;}private void topologicalSortUtil(Vertex vertex, Set<Vertex> visited, Stack<Vertex> stack) {visited.add(vertex);for (Vertex neighbor : adjacencyList.get(vertex)) {if (!visited.contains(neighbor)) {topologicalSortUtil(neighbor, visited, stack);}}stack.push(vertex);}// 打印图的顶点和边public void printGraph() {for (Map.Entry<Vertex, List<Vertex>> entry : adjacencyList.entrySet()) {System.out.print(entry.getKey() + " -> ");for (Vertex vertex : entry.getValue()) {System.out.print(vertex + " ");}System.out.println();}}public static void main(String[] args) {DAG graph = new DAG();graph.addVertex("A");graph.addVertex("B");graph.addVertex("C");graph.addVertex("D");graph.addEdge("A", "B");graph.addEdge("A", "C");graph.addEdge("B", "D");graph.addEdge("C", "D");graph.addEdge("B", "A");System.out.println("图的顶点和边:");graph.printGraph();System.out.println("\n拓扑排序:");List<Vertex> sortedList = graph.topologicalSort();for (Vertex vertex : sortedList) {System.out.print(vertex + " ");}}
}

QA:待定

http://www.lryc.cn/news/365373.html

相关文章:

  • QuanTA: 一种新的高秩高效微调范式
  • 【漏洞复现】用友NC downCourseWare 任意文件读取漏洞
  • 度安讲 | 第二期「安全左移·业务护航」技术沙龙成功举办
  • 代码片段 | Matlab三维图显示[ R T 0 1] 的最佳方法
  • 2024百度之星 跑步
  • 【git】TortoiseGitPlink Fatal Error 解决方法
  • 行心科技|中科利众:健康科技新合作,营养与科技融合前行
  • Xcode 打包报错Command PhaseScriptExecution failed with a nonzero exit code
  • 使用 IPSET 添加 CDN 节点 IP(IPv4/IPv6)到防火墙白名单
  • oracle trim 函数很慢,加trim以后执行超慢,执行计划求解
  • 【Leetcode Python】
  • Ubuntu系统的k8s常见的错误和解决的问题
  • Scala学习笔记7: 对象
  • 【Linux】进程切换环境变量
  • 嵌入式学习记录6.6(拷贝构造/友元函数/常成员函数)
  • 宝塔 nginx 配置负载均衡 upstream
  • idea 插件推荐
  • 【Linux】Linux环境基础开发工具_5
  • Java Web学习笔记15——DOM对象
  • 中电联系列一:rocket手把手教你理解中电联协议!
  • (面试官问我微服务与naocs的使用我回答了如下,面试官让我回去等通知)微服务拆分与nacos的配置使用
  • 冯喜运:6.7今日黄金原油行情分析及独家操作策略
  • Android 蓝牙概述
  • Python3 笔记:字符串的 find()、rfind()、index()、rindex()
  • 【研发日记】Matlab/Simulink软件优化(二)——通信负载柔性均衡算法
  • Python 设计模式(行为型)
  • 电商API商品数据采集接口||助力电商企业采集商品大数据提高开发效率
  • Day34 事件聚合器实现消息过滤功能
  • 前端 JS 经典:Reflect 本质
  • accelerate 的一个tip:early stopping 处可能存在的bug