图论11-欧拉回路与欧拉路径+Hierholzer算法实现

news/2024/11/19 9:20:42/

文章目录

  • 1 欧拉回路的概念
  • 2 欧拉回路的算法实现
  • 3 Hierholzer算法详解
  • 4 Hierholzer算法实现
    • 4.1 修改Graph,增加API
    • 4.2 Graph.java
    • 4.3 联通分量类
    • 4.4 欧拉回路类

1 欧拉回路的概念

在这里插入图片描述

在这里插入图片描述

2 欧拉回路的算法实现

private boolean hasEulerLoop(){CC cc = new CC(G);if(cc.count() > 1) return false;for(int v = 0; v < G.V(); v ++)if(G.degree(v) % 2 == 1) return false;return true;
}

3 Hierholzer算法详解

在这里插入图片描述

public ArrayList<Integer> result(){ArrayList<Integer> res = new ArrayList<>();if(!hasEulerLoop()) return res;//根据小g进行删边Graph g = (Graph)G.clone();Stack<Integer> stack = new Stack<>();int curv = 0; //出发点stack.push(curv);while(!stack.isEmpty()){if(g.degree(curv) != 0){stack.push(curv);int w = g.adj(curv).iterator().next();g.removeEdge(curv, w);curv = w;}else{res.add(curv);curv = stack.pop();}}return res;
}

4 Hierholzer算法实现

4.1 修改Graph,增加API

//移除边
public void removeEdge(int v, int w){validateVertex(v);validateVertex(w);if(adj[v].contains(w)) E --;adj[v].remove(w);adj[w].remove(v);
}//深拷贝
@Override
public Object clone(){try{Graph cloned = (Graph) super.clone();cloned.adj = new TreeSet[V];for(int v = 0; v < V; v ++){cloned.adj[v] = new TreeSet<Integer>();for(int w: adj[v])cloned.adj[v].add(w);}return cloned;}catch (CloneNotSupportedException e){e.printStackTrace();}return null;
}

4.2 Graph.java

package Chapter08_EulerLoop_And_EulerPath;import java.io.File;
import java.io.IOException;
import java.util.TreeSet;
import java.util.Scanner;/// 暂时只支持无向无权图
public class Graph implements Cloneable{private int V;private int E;private TreeSet<Integer>[] adj;public Graph(String filename){File file = new File(filename);try(Scanner scanner = new Scanner(file)){V = scanner.nextInt();if(V < 0) throw new IllegalArgumentException("V must be non-negative");adj = new TreeSet[V];for(int i = 0; i < V; i ++)adj[i] = new TreeSet<Integer>();E = scanner.nextInt();if(E < 0) throw new IllegalArgumentException("E must be non-negative");for(int i = 0; i < E; i ++){int a = scanner.nextInt();validateVertex(a);int b = scanner.nextInt();validateVertex(b);if(a == b) throw new IllegalArgumentException("Self Loop is Detected!");if(adj[a].contains(b)) throw new IllegalArgumentException("Parallel Edges are Detected!");adj[a].add(b);adj[b].add(a);}}catch(IOException e){e.printStackTrace();}}public void validateVertex(int v){if(v < 0 || v >= V)throw new IllegalArgumentException("vertex " + v + "is invalid");}public int V(){return V;}public int E(){return E;}public boolean hasEdge(int v, int w){validateVertex(v);validateVertex(w);return adj[v].contains(w);}public Iterable<Integer> adj(int v){validateVertex(v);return adj[v];}public int degree(int v){validateVertex(v);return adj[v].size();}public void removeEdge(int v, int w){validateVertex(v);validateVertex(w);if(adj[v].contains(w)) E --;adj[v].remove(w);adj[w].remove(v);}@Overridepublic Object clone(){try{Graph cloned = (Graph) super.clone();cloned.adj = new TreeSet[V];for(int v = 0; v < V; v ++){cloned.adj[v] = new TreeSet<Integer>();for(int w: adj[v])cloned.adj[v].add(w);}return cloned;}catch (CloneNotSupportedException e){e.printStackTrace();}return null;}@Overridepublic String toString(){StringBuilder sb = new StringBuilder();sb.append(String.format("V = %d, E = %d\n", V, E));for(int v = 0; v < V; v ++){sb.append(String.format("%d : ", v));for(int w : adj[v])sb.append(String.format("%d ", w));sb.append('\n');}return sb.toString();}public static void main(String[] args){Graph g = new Graph("g.txt");System.out.print(g);}
}

4.3 联通分量类

package Chapter08_EulerLoop_And_EulerPath;import java.util.ArrayList;public class CC {private Graph G;private int[] visited;private int cccount = 0;public CC(Graph G){this.G = G;visited = new int[G.V()];for(int i = 0; i < visited.length; i ++)visited[i] = -1;for(int v = 0; v < G.V(); v ++)if(visited[v] == -1){dfs(v, cccount);cccount ++;}}private void dfs(int v, int ccid){visited[v] = ccid;for(int w: G.adj(v))if(visited[w] == -1)dfs(w, ccid);}public int count(){return cccount;}public boolean isConnected(int v, int w){G.validateVertex(v);G.validateVertex(w);return visited[v] == visited[w];}public ArrayList<Integer>[] components(){ArrayList<Integer>[] res = new ArrayList[cccount];for(int i = 0; i < cccount; i ++)res[i] = new ArrayList<Integer>();for(int v = 0; v < G.V(); v ++)res[visited[v]].add(v);return res;}public static void main(String[] args){Graph g = new Graph("g.txt");CC cc = new CC(g);System.out.println(cc.count());System.out.println(cc.isConnected(0, 6));System.out.println(cc.isConnected(5, 6));ArrayList<Integer>[] comp = cc.components();for(int ccid = 0; ccid < comp.length; ccid ++){System.out.print(ccid + " : ");for(int w: comp[ccid])System.out.print(w + " ");System.out.println();}}
}

4.4 欧拉回路类

package Chapter08_EulerLoop_And_EulerPath;import java.util.ArrayList;
import java.util.Stack;public class EulerLoop {private Graph G;public EulerLoop(Graph G){this.G = G;}private boolean hasEulerLoop(){CC cc = new CC(G);if(cc.count() > 1) return false;for(int v = 0; v < G.V(); v ++)if(G.degree(v) % 2 == 1) return false;return true;}public ArrayList<Integer> result(){ArrayList<Integer> res = new ArrayList<>();if(!hasEulerLoop()) return res;Graph g = (Graph)G.clone();Stack<Integer> stack = new Stack<>();int curv = 0;stack.push(curv);while(!stack.isEmpty()){if(g.degree(curv) != 0){stack.push(curv);int w = g.adj(curv).iterator().next();g.removeEdge(curv, w);curv = w;}else{res.add(curv);curv = stack.pop();}}return res;}public static void main(String[] args){Graph g = new Graph("g8.txt");EulerLoop el = new EulerLoop(g);System.out.println(el.result());Graph g2 = new Graph("g2.txt");EulerLoop el2 = new EulerLoop(g2);System.out.println(el2.result());}
}

在这里插入图片描述


http://www.ppmy.cn/news/1211615.html

相关文章

linux入门---线程池的模拟实现

目录标题 什么是线程池线程的封装准备工作构造函数和析构函数start函数join函数threadname函数完整代码 线程池的实现准备工作构造函数和析构函数push函数pop函数run函数完整的代码 测试代码 什么是线程池 在实现线程池之前我们先了解一下什么是线程池&#xff0c;所谓的池大家…

Web相机和浏览器的二维码扫描方案

Web相机和适用于浏览器的二维码扫描方案 qr-camera 在线体验 | English 功能 支持浏览器扫描二维码支持拍照支持录像功能支持二维码解析和生成 quickstart npm i qr-cameraimport {QRCamera} from qr-camera;function main(){const camera new QRCamera();document.body…

安卓常见设计模式14------单例模式(Kotlin版)

1. W1 是什么&#xff0c;什么是单例模式&#xff1f;​ 单例模式属于创建型模式&#xff0c;旨在确保一个类只有一个实例&#xff0c;并提供一个全局访问点来获取该实例。单例模式的核心思想是限制类的实例化&#xff0c;使得系统中只有一个共享的实例。 2. W2 为什么&#…

SpringBoot 项目公共字段填充

[公共字段自动填充] 核心&#xff1a;在切面类中捕获需要填充公共字段的 Mapper 方法&#xff0c;方法上使用注解加以标识&#xff0c;通过反射拿到需要填充的字段赋值方法&#xff0c;进行赋值操作 1、自定义注解 AutoFill Target(ElementType.METHOD) Retention(RetentionPo…

Visual Studio 2019下编译OpenCV 4.7 与OpenCV 4.7 contrib

一、环境 使用的环境是Win10,Visual Studio 2019,Cmake3.28,cdua 11.7&#xff0c;cudnn 8.5,如果只是在CPU环境下使用&#xff0c;则不用安装CUDA。要使用GPU处理&#xff0c;安装好CUDA之后&#xff0c;要测试安装的CUDA是否能用。不能正常使用的话&#xff0c;添加一下系统…

CSS的初步学习

CSS 层叠样式表 (Cascading Style Sheets). CSS 能够对网页中元素位置的排版进行像素级精确控制, 实现美化页面的效果. 能够做到页面的样式和结 构分离. CSS 就是 “东方四大邪术” 之化妆术 CSS 基本语法规范: 选择器 若干属性声明 选择器决定针对谁修改 (找谁) 声明决定修…

EM@比例恒等式@分式恒等式

文章目录 比例恒等式(分式恒等式)分式等式链例 比例恒等式(分式恒等式) 设 a b c d \frac{a}{b}\frac{c}{d} ba​dc​(0)令这个比值为 k k k,则 a k b akb akb(0-1), c k d ckd ckd(0-2),以下恒等式在表达式有意义的情形下成立(例如分母不为0) 合比定理: a b b c d d \f…

各种ui框架的 form校验 validator获取不到value

// form-item 配置prop prop"user.name" // rules rules: {user.name: [message: "xxxxx",validator(rule, val, callback) {// val 就是user.name的值},] }如: 对象的sysUser.userName <n-form ref"formRefuser" :model"modelUser&qu…