草庐IT

图论(五)图的深度优先遍历DFS

小波同学 2023-03-28 原文

一、深度优先遍历

深度优先遍历,从初始访问结点出发,我们知道初始访问结点可能有多个邻接结点,深度优先遍历的策略就是首先访问第一个邻接结点,然后再以这个被访问的邻接结点作为初始结点,访问它的第一个邻接结点。总结起来可以这样说:每次都在访问完当前结点后首先访问当前结点的第一个邻接结点。

我们从这里可以看到,这样的访问策略是优先往纵向挖掘深入,而不是对一个结点的所有邻接结点进行横向访问。

具体算法表述如下:

  • 1、访问初始结点v,并标记结点v为已访问。
  • 2、查找结点v的第一个邻接结点w。
  • 3、若w存在,则继续执行4,否则算法结束。
  • 4、若w未被访问,对w进行深度优先遍历递归(即把w当做另一个v,然后进行步骤123)。
  • 5、查找结点v的w邻接结点的下一个邻接结点,转到步骤3。

二、邻接表进行深度优先遍历

2.1 构建数据结构

public class Graph {

    //顶点个数
    private int V;

    //边的条数
    private int E;

    //领接表的底层存储结构
    private TreeSet<Integer>[] adj;

}

2.2 通过该结构定义,我们构造一个图(无向图)

/**
 * @Author: huangyibo
 * @Date: 2022/3/28 1:02
 * @Description: 领接表, 目前只支持无向无权图
 */

public class Graph {

    //顶点个数
    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<>();
            }

            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();
                //校验顶点a是否合法
                validateVertex(a);

                int b = scanner.nextInt();
                //校验顶点b是否合法
                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 (FileNotFoundException e) {
            e.printStackTrace();
        }
    }

    /**
     * 校验顶点是否合法
     * @param v
     */
    private void validateVertex(int v){
        if(v < 0 || v >= V){
            throw new IllegalArgumentException("vertex " + v + " is invalid");
        }
    }

    /**
     * 获取顶点个数
     * @return
     */
    public int V(){
        return V;
    }

    /**
     * 获取边的条数
     * @return
     */
    public int E(){
        return E;
    }

    /**
     * 图中是否存在v到w的边
     * @param v
     * @param w
     * @return
     */
    public boolean hasEdge(int v, int w){
        //校验顶点v是否合法
        validateVertex(v);
        //校验顶点w是否合法
        validateVertex(w);
        return adj[v].contains(w);
    }

    /**
     * 返回和v相邻的顶点
     * @param v
     * @return
     */
    public Iterable<Integer> adj(int v){
        //校验顶点v是否合法
        validateVertex(v);
        return adj[v];
    }

    /**
     * 返回顶点v的度
     * 顶点v的度(Degree)是指在图中与v相关联的边的条数
     * @param v
     * @return
     */
    public int degree(int v){
        //校验顶点v是否合法
        validateVertex(v);
        return adj[v].size();
    }

    @Override
    public 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 (Integer w : adj[v]) {
                sb.append(String.format("%d ", w));
            }
            sb.append("\n");
        }
        return sb.toString();
    }
}

2.3 邻接表的深度优先递归算法

/**
 * @Author: huangyibo
 * @Date: 2022/3/28 1:02
 * @Description: 图的深度优先遍历
 */

public class GraphDFS {

    private Graph G;

    /**
     * 图的顶点是否已经被遍历过
     */
    private boolean[] visited;

    //图的深度优先遍历前序遍历结果
    private List<Integer> pre = new ArrayList<>();

    //图的深度优先遍历后序遍历结果
    private List<Integer> post = new ArrayList<>();

    public GraphDFS(Graph G){
        this.G = G;
        visited = new boolean[G.V()];
        //循环所有顶点, 防止一个图出现多个连通图(连通分量)的情况
        for (int v = 0; v < G.V(); v++) {
            if(!visited[v]){
                dfs(v);
            }
        }
    }

    /**
     * 图的深度优先遍历
     * @param v
     */
    private void dfs(int v) {
        visited[v] = true;
        pre.add(v);
        for (Integer w : G.adj(v)) {
            if(!visited[w]){
                dfs(w);
            }
        }
        post.add(v);
    }

    public List<Integer> pre(){
        return pre;
    }

    public List<Integer> post(){
        return post;
    }

    public static void main(String[] args) {
        Graph graph = new Graph("src/main/resources/g1.txt");
        GraphDFS graphDFS = new GraphDFS(graph);
        System.out.println(graphDFS.pre());
        System.out.println(graphDFS.post());
    }
}

g1.txt

7 6
0 1
0 2
1 3
1 4
2 3
2 6

三、基于深度优先遍历的应用

3.1 求解联通分量

  • 1、图的联通分量个数
  • 2、判断两个顶点是否在同一个联通分量中
  • 3、图中不同的联通分量对应的顶点
/**
 * @Author: huangyibo
 * @Date: 2022/3/28 1:02
 * @Description: 基于图的深度优先遍历、求解联通分量
 */

public class ConnectedGraph {

    private Graph G;

    //图的顶点是否已经被遍历过
    private int[] visited;

    //图的联通分量个数
    private Integer ccCount = 0;

    public ConnectedGraph(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 ++;
            }
        }
    }

    /**
     * 图的深度优先遍历
     * @param v
     */
    private void dfs(int v, int ccId) {
        visited[v] = ccId;
        for (Integer w : G.adj(v)) {
            if(visited[w] == -1){
                dfs(w, ccId);
            }
        }
    }

    public Integer count(){
        return ccCount;
    }

    /**
     * 判断顶点v和w是否在同一个联通分量中
     * @param v
     * @param w
     * @return
     */
    public boolean isConnected(int v, int w){
        //校验顶点v是否合法
        G.validateVertex(v);
        //校验顶点w是否合法
        G.validateVertex(w);
        return visited[v] == visited[w];
    }

    /**
     * 返回图中不同的联通分量对应的顶点
     * @return
     */
    public List<Integer>[] components(){
        List<Integer>[] lists = new ArrayList[ccCount];
        for (int i = 0; i < ccCount; i++) {
            lists[i] = new ArrayList<>();
        }
        for (int v = 0; v < G.V(); v++) {
            lists[visited[v]].add(v);
        }
        return lists;
    }

    public static void main(String[] args) {
        Graph graph = new Graph("src/main/resources/g1.txt");
        ConnectedGraph ccGraph = new ConnectedGraph(graph);
        System.out.println(ccGraph.count());
        System.out.println(ccGraph.isConnected(0, 6));
        System.out.println(ccGraph.isConnected(0, 5));
        List<Integer>[] components = ccGraph.components();
        for (List<Integer> component : components) {
            System.out.println(component);
        }
    }
}

3.2 求解单源路径问题

/**
 * @Author: huangyibo
 * @Date: 2022/3/28 1:02
 * @Description: 基于图的深度优先遍历、求解单源路径问题
 */

public class SingleSourcePath {

    private Graph G;

    //源
    private int source;

    /**
     * 图的顶点是否已经被遍历过
     */
    private boolean[] visited;

    /**
     * 存储的是当前访问节点的前一个节点的值
     */
    private int[] pre;

    public SingleSourcePath(Graph G, int source){
        G.validateVertex(source);
        this.G = G;
        this.source = source;
        visited = new boolean[G.V()];
        pre = new int[G.V()];
        //pre数组的所有元素赋值为-1
        Arrays.fill(pre, -1);
        //单源路径问题,深度遍历从顶点s开始
        dfs(source, source);
    }

    /**
     * 图的深度优先遍历
     * @param v         当前节点
     * @param parent    当前节点的上一个节点
     */
    private void dfs(int v, int parent) {
        visited[v] = true;
        pre[v] = parent;
        for (Integer w : G.adj(v)) {
            if(!visited[w]){
                dfs(w, v);
            }
        }
    }

    /**
     * 判断源s到顶点target是否可达
     * @param target
     * @return
     */
    public boolean isConnectedTo(int target){
        G.validateVertex(target);
        return visited[target];
    }

    /**
     * 源s到顶点target的路径
     * @param target
     * @return
     */
    public List<Integer> path(int target){
        List<Integer> result = new ArrayList<>();
        if(!isConnectedTo(target)){
            //源s到顶点target不可达, 直接返回空集合
            return result;
        }
        int cur = target;
        while(cur != source){
            result.add(cur);
            cur = pre[cur];
        }
        result.add(source);
        Collections.reverse(result);
        return result;
    }

    public static void main(String[] args) {
        Graph graph = new Graph("src/main/resources/g1.txt");
        SingleSourcePath ssPath = new SingleSourcePath(graph, 0);
        System.out.println("0 -> 6 : " + ssPath.path(6));
        System.out.println("0 -> 5 : " + ssPath.path(5));
    }
}

3.3 求解两点之间是否有路径问题

/**
 * @Author: huangyibo
 * @Date: 2022/3/28 1:02
 * @Description: 基于图的深度优先遍历、求解两点之间是否有路径问题
 */

public class Path {

    private Graph G;

    //源点
    private int source;

    //终止点
    private int target;

    /**
     * 图的顶点是否已经被遍历过
     */
    private boolean[] visited;

    /**
     * 存储的是当前访问节点的前一个节点的值
     */
    private int[] pre;

    public Path(Graph G, int source, int target){
        G.validateVertex(source);
        G.validateVertex(target);
        this.G = G;
        this.source = source;
        this.target = target;
        visited = new boolean[G.V()];
        pre = new int[G.V()];
        //pre数组的所有元素赋值为-1
        Arrays.fill(pre, -1);
        //单源路径问题,深度遍历从顶点s开始
        dfs(source, source);
    }

    /**
     * 图的深度优先遍历
     * @param v         当前节点
     * @param parent    当前节点的上一个节点
     */
    private boolean dfs(int v, int parent) {
        visited[v] = true;
        pre[v] = parent;
        if(v == target){
            return true;
        }
        for (Integer w : G.adj(v)) {
            if(!visited[w]){
                if(dfs(w, v)){
                    return true;
                }
            }
        }
        return false;
    }

    /**
     * 判断源s到顶点target是否可达
     * @return
     */
    public boolean isConnected(){
        return visited[target];
    }

    /**
     * 源s到顶点target的路径
     * @return
     */
    public List<Integer> path(){
        List<Integer> result = new ArrayList<>();
        if(!isConnected()){
            //源s到顶点target不可达, 直接返回空集合
            return result;
        }
        int cur = target;
        while(cur != source){
            result.add(cur);
            cur = pre[cur];
        }
        result.add(source);
        Collections.reverse(result);
        return result;
    }

    public static void main(String[] args) {
        Graph graph = new Graph("src/main/resources/g1.txt");
        Path path = new Path(graph, 0, 6);
        System.out.println("0 -> 6 : " + path.path());

        Path path2 = new Path(graph, 0, 1);
        System.out.println("0 -> 1 : " + path2.path());

        Path path3 = new Path(graph, 0, 5);
        System.out.println("0 -> 5 : " + path3.path());

    }
}

3.4 无向图的环检测

/**
 * @Author: huangyibo
 * @Date: 2022/4/9 16:16
 * @Description: 基于图的深度优先遍历、求解无向图的环检测问题
 */

public class CycleDetection {


    private Graph G;

    /**
     * 图的顶点是否已经被遍历过
     */
    private boolean[] visited;

    private boolean hasCycle = false;

    public CycleDetection(Graph G){
        this.G = G;
        visited = new boolean[G.V()];
        //循环所有顶点, 防止一个图出现多个连通图(连通分量)的情况
        for (int v = 0; v < G.V(); v++) {
            if(!visited[v]){
                if(dfs(v, v)){
                    hasCycle = true;
                    break;
                }
            }
        }
    }

    /**
     * 图的深度优先遍历
     * 从顶点V开始,判断图是否有环
     * @param v
     */
    private boolean dfs(int v, int parent) {
        visited[v] = true;
        for (Integer w : G.adj(v)) {
            if(!visited[w]){
                if(dfs(w, v)){
                    return true;
                }
            }else if(w != parent){
                //表示图有环
                return true;
            }
        }
        return false;
    }

    /**
     * 图是否有环
     * @return
     */
    public boolean hasCycle(){
        return hasCycle;
    }

    public static void main(String[] args) {
        Graph graph1 = new Graph("src/main/resources/g1.txt");
        CycleDetection cycleDetection1 = new CycleDetection(graph1);
        System.out.println(cycleDetection1.hasCycle);

        Graph graph2 = new Graph("src/main/resources/g2.txt");
        CycleDetection cycleDetection2 = new CycleDetection(graph2);
        System.out.println(cycleDetection2.hasCycle);
    }
}

3.5 二分图的检测

/**
 * @Author: huangyibo
 * @Date: 2022/3/28 1:02
 * @Description: 基于图的深度优先遍历、二分图的检测
 */

public class BipartitionDetection {

    private Graph G;

    /**
     * 图的顶点是否已经被遍历过
     */
    private boolean[] visited;

    /**
     * 顶点的颜色数组
     */
    private int[] colors;

    //是否是二分图
    private boolean isBipartite = true;

    public BipartitionDetection(Graph G){
        this.G = G;
        visited = new boolean[G.V()];
        colors = new int[G.V()];
        for (int i = 0; i < G.V(); i++) {
            colors[i] = -1;
        }
        //循环所有顶点, 防止一个图出现多个连通图(连通分量)的情况
        for (int v = 0; v < G.V(); v++) {
            if(!visited[v]){
                if(!dfs(v, 0)){
                    isBipartite = false;
                    break;
                }
            }
        }
    }

    /**
     * 图的深度优先遍历
     * @param v
     */
    private boolean dfs(int v, int color) {
        visited[v] = true;
        colors[v] = color;
        for (Integer w : G.adj(v)) {
            if(!visited[w]){
                if(!dfs(w, 1 - color)){
                    return false;
                }
            }else if(colors[w] == colors[v]){
                return false;
            }
        }
        return true;
    }

    /**
     * 是否是二分图
     * @return
     */
    public boolean isBipartite(){
        return isBipartite;
    }

    public static void main(String[] args) {
        Graph graph = new Graph("src/main/resources/g1.txt");
        BipartitionDetection bd = new BipartitionDetection(graph);
        System.out.println(bd.isBipartite());
    }
}

参考:
https://zhuanlan.zhihu.com/p/138073414

https://zhuanlan.zhihu.com/p/138073414

有关图论(五)图的深度优先遍历DFS的更多相关文章

  1. ruby-on-rails - 在 Ruby 中循环遍历多个数组 - 2

    我有多个ActiveRecord子类Item的实例数组,我需要根据最早的事件循环打印。在这种情况下,我需要打印付款和维护日期,如下所示:ItemAmaintenancerequiredin5daysItemBpaymentrequiredin6daysItemApaymentrequiredin7daysItemBmaintenancerequiredin8days我目前有两个查询,用于查找maintenance和payment项目(非排他性查询),并输出如下内容:paymentrequiredin...maintenancerequiredin...有什么方法可以改善上述(丑陋的)代

  2. 深度学习部署:Windows安装pycocotools报错解决方法 - 2

    深度学习部署:Windows安装pycocotools报错解决方法1.pycocotools库的简介2.pycocotools安装的坑3.解决办法更多Ai资讯:公主号AiCharm本系列是作者在跑一些深度学习实例时,遇到的各种各样的问题及解决办法,希望能够帮助到大家。ERROR:Commanderroredoutwithexitstatus1:'D:\Anaconda3\python.exe'-u-c'importsys,setuptools,tokenize;sys.argv[0]='"'"'C:\\Users\\46653\\AppData\\Local\\Temp\\pip-instal

  3. 【Java入门】使用Java实现文件夹的遍历 - 2

    遍历文件夹我们通常是使用递归进行操作,这种方式比较简单,也比较容易理解。本文为大家介绍另一种不使用递归的方式,由于没有使用递归,只用到了循环和集合,所以效率更高一些!一、使用递归遍历文件夹整体思路1、使用File封装初始目录,2、打印这个目录3、获取这个目录下所有的子文件和子目录的数组。4、遍历这个数组,取出每个File对象4-1、如果File是否是一个文件,打印4-2、否则就是一个目录,递归调用代码实现publicclassSearchFile{publicstaticvoidmain(String[]args){//初始目录Filedir=newFile("d:/Dev");Datebeg

  4. ruby - Chef Ruby 遍历 .erb 模板文件中的属性 - 2

    所以这可能有点令人困惑,但请耐心等待。简而言之,我想遍历具有特定键值的所有属性,然后如果值不为空,则将它们插入到模板中。这是我的代码:属性:#===DefaultfileConfigurations#default['elasticsearch']['default']['ES_USER']=''default['elasticsearch']['default']['ES_GROUP']=''default['elasticsearch']['default']['ES_HEAP_SIZE']=''default['elasticsearch']['default']['MAX_OP

  5. ruby - 如何遍历 Ruby 中所有正则表达式匹配的字符串? - 2

    我们有一个字符串:“”这个正则表达式://i如何从当前字符串中获取所有匹配项? 最佳答案 "".scan(//)参见scan在ruby​​-docs上 关于ruby-如何遍历Ruby中所有正则表达式匹配的字符串?,我们在StackOverflow上找到一个类似的问题: https://stackoverflow.com/questions/6857852/

  6. ruby - 循环遍历数组的元素 - 2

    我想从0到2循环@a:0,1,2,0,1,2。defset_aif@a==2@a=0else@a=@a+1endend也许有更好的方法? 最佳答案 (0..2).cycle(3){|x|putsx}#=>0,1,2,0,1,2,0,1,2item=[0,1,2].cycle.eachitem.next#=>0item.next#=>1item.next#=>2item.next#=>0... 关于ruby-循环遍历数组的元素,我们在StackOverflow上找到一个类似的问题:

  7. 深度学习12. CNN经典网络 VGG16 - 2

    深度学习12.CNN经典网络VGG16一、简介1.VGG来源2.VGG分类3.不同模型的参数数量4.3x3卷积核的好处5.关于学习率调度6.批归一化二、VGG16层分析1.层划分2.参数展开过程图解3.参数传递示例4.VGG16各层参数数量三、代码分析1.VGG16模型定义2.训练3.测试一、简介1.VGG来源VGG(VisualGeometryGroup)是一个视觉几何组在2014年提出的深度卷积神经网络架构。VGG在2014年ImageNet图像分类竞赛亚军,定位竞赛冠军;VGG网络采用连续的小卷积核(3x3)和池化层构建深度神经网络,网络深度可以达到16层或19层,其中VGG16和VGG

  8. ruby-on-rails - 如何在 Rails View 中遍历数组? - 2

    我在MySql中进行了查询,但在Rails和mysql2gem中工作。信息如下:http://sqlfiddle.com/#!2/9adb8/6查询工作正常,没有问题,并显示以下结果:UNITV1A1N1V2A2N2V3A3N3V4A4N4V5A5N5LIFE200120000000000ROB010012000000000-为rails2.3.8安装了mysql2gemgeminstallmysql2-v0.2.6-创建Controller:classPolicyController这是日志:SQL(0.9ms)selectdistinct@sql:=concat('SELECTpb

  9. ruby - Ruby 中的目录遍历 - 2

    我一直在尝试使用简单的递归方法在Ruby中为一个更大的程序的一部分实现目录遍历。但是我发现Dir.foreach不包括其中的目录。我怎样才能列出它们?代码:defwalk(start)Dir.foreach(start)do|x|ifx=="."orx==".."nextelsifFile.directory?(x)walk(x)elseputsxendendend 最佳答案 问题是每次递归,你传递给File.directory?的路径isno只是实体(文件或目录)名称;所有上下文都丢失了。所以说你进入one/two/three/检

  10. ruby - 了解 Ruby 中赋值和逻辑运算符的优先级 - 2

    在以下示例中,我无法理解Ruby运算符的优先级:x=1&&y=2由于&&的优先级高于=,我的理解是类似于+和*运算符:1+2*3+4解析为1+(2*3)+4它应该等于:x=(1&&y)=2但是,所有Ruby源代码(包括内部语法解析器Ripper)都将其解析为x=(1&&(y=2))为什么?编辑[08.01.2016]让我们关注一个子表达式:1&&y=2根据优先规则,我们应该尝试将其解析为:(1&&y)=2这没有意义,因为=需要特定的LHS(变量、常量、[]数组项等)。但是既然(1&&y)是一个正确的表达式,那么解析器应该如何处理呢?我试过咨询Ruby的parse.y,但它太像意大利面条

随机推荐