日撸 Java 三百行day34

news2024/9/20 22:30:34

文章目录

  • 说明
  • Day34 图的深度优先遍历
    • 1.思路
    • 2.代码
    • 3.总结
      • 1.在广度遍历中借助了队列
      • 2.在深度优先遍历借助了栈。

说明

闵老师的文章链接: 日撸 Java 三百行(总述)_minfanphd的博客-CSDN博客
自己也把手敲的代码放在了github上维护:https://github.com/fulisha-ok/sampledata

Day34 图的深度优先遍历

1.思路

相比于广度优先遍历,深度优先遍历是往深度遍历,深度遍历更像是树的先根遍历。深度遍历借助栈来实现,如下图,从a节点出发,先访问a后再将a入栈,直到访问到f无法再往深度访问则是就往回溯,回溯上一个节点,看他的领接点,再对领接点进行深度遍历,最后将节点都遍历完。
在这里插入图片描述
根据上图画出相应的矩阵
Δ a b c d e f a 0 1 1 0 0 0 b 1 0 0 1 0 0 c 0 0 0 1 1 0 d 0 0 0 0 1 1 e 0 0 0 0 0 0 f 0 0 0 0 0 0 \begin{array}{c} % 总表格 \begin{array}{c|cccc} % 第二行 Delta 值数组 \Delta & a & b & c & d & e & f \\ \hline a & 0 & 1 & 1 & 0 & 0 & 0 \\ b & 1 & 0 & 0 & 1 & 0 & 0 \\ c & 0 & 0 & 0 & 1 & 1 & 0\\ d & 0 & 0 & 0 & 0 & 1 & 1 \\ e & 0 & 0 & 0 & 0 & 0 & 0 \\ f & 0 & 0 & 0 & 0 & 0 & 0 \\ \end{array} % 第二行表格结束 \end{array} % 总表格结束 Δabcdefa010000b100000c100000d011000e001100f000100

假如我们从a点出发,我们初始化栈时,会将a压入栈中。现在a出栈,同时a的领接点b入栈;接下来将b的领节点d入栈;再将d的领节点(e或f)入栈,这里选择f, 发现f没有领结点,则是就开始回溯,f出栈,然后d出栈,判断d的领结点有没有访问过,发现f被访问过,e没有,则将e压入栈中,然后又从e节点开始往下深度找,和上面步骤一样。在这个过程中主要注意有几点:

  • 1.何时入栈
    当所访问的节点还有邻结点且没有被访问,则继续将孩子节点进行入栈
  • 2.何时出栈
    当发现访问节点没有孩子节点,自己就需要出栈,且要往回回溯节点。

2.代码

在深度遍历的代码中,while(true)这个循环一定要有退出循环的条件,不然会进入死循环。在循环中的tempNext变量则是往深度找节点的变量,当往最深不能再走,则节点出栈(栈:先进后出)回溯。

  • 和day33代码一样,如果有多个连通分量 可能回漏掉结点,所以也加了一个判断,tempVisitedArray,resultString作为成员变量,breadthTraversal和depthTraversal方法是保证所有结点都能访问到,在方法开始前都会重新初始化tempVisitedArray,resultString这两个变量。
    代码如下:
package graph;

import datastructure.queue.CircleObjectQueue;
import datastructure.stack.ObjectStack;
import matrix.IntMatrix;

import java.time.Year;

/**
 * @author: fulisha
 * @date: 2023/4/18 15:43
 * @description:
 */
public class Graph {

    IntMatrix connectivityMatrix;

    /**
     * The first constructor.
     * @param paraNumNodes The number of nodes in the graph.
     */
    public Graph(int paraNumNodes){
        connectivityMatrix = new IntMatrix(paraNumNodes, paraNumNodes);
    }

    /**
     * The second constructor.
     * @param paraMatrix The data matrix.
     */
    public Graph(int[][] paraMatrix){
        connectivityMatrix = new IntMatrix(paraMatrix);
    }

    @Override
    public String toString(){
        return "This is the connectivity matrix of the graph.\r\n" + connectivityMatrix;
    }

    /**
     * Get the connectivity of the graph.
     * @return
     */
    public boolean getConnectivity() throws Exception {
        // Step 1. Initialize accumulated matrix.
        IntMatrix tempConnectivityMatrix = IntMatrix.getIdentityMatrix(connectivityMatrix.getData().length);

        //Step 2. Initialize
        IntMatrix tempMultipliedMatrix = new IntMatrix(connectivityMatrix);

        //Step 3. Determine the actual connectivity.
        for (int i = 0; i < connectivityMatrix.getData().length - 1; i++){
            // M_a = M_a + M^k
            tempConnectivityMatrix.add(tempMultipliedMatrix);
            // M^k
            tempMultipliedMatrix = IntMatrix.multiply(tempMultipliedMatrix, connectivityMatrix);
        }

        // Step 4. Check the connectivity.
        System.out.println("The connectivity matrix is: " + tempConnectivityMatrix);
        int[][] tempData = tempConnectivityMatrix.getData();
        for (int i = 0; i < tempData.length; i++) {
            for (int j = 0; j < tempData.length; j++){
                if (tempData[i][j] == 0){
                    System.out.println("Node " + i + " cannot reach " + j);
                    return false;
                }
            }
        }
        return true;
    }

    /**
     * Unit test for getConnectivity.
     */
    public static void getConnectivityTest(){
        int[][] tempMatrix = { { 0, 1, 0 }, { 1, 0, 1 }, { 0, 1, 0 } };
        Graph tempGraph2 = new Graph(tempMatrix);
        System.out.println(tempGraph2);

        boolean tempConnected = false;
        try {
            tempConnected = tempGraph2.getConnectivity();
        } catch (Exception ee) {
            System.out.println(ee.getMessage());
        }
        System.out.println("Is the graph connected? " + tempConnected);

        //Test a directed graph. Remove one arc to form a directed graph.
        tempGraph2.connectivityMatrix.setValue(1, 0, 0);
        tempConnected = false;
        try {
            tempConnected = tempGraph2.getConnectivity();
        } catch (Exception ee) {
            System.out.println(ee);
        }

        System.out.println("Is the graph connected? " + tempConnected);

    }

    /**
     * Breadth first Traversal
     * @param paraStartIndex The start index.
     * @return The sequence of the visit.
     */
    boolean[] tempVisitedArray;
    String resultString = "";
    public String breadthFirstTraversal(int paraStartIndex) {
        CircleObjectQueue tempQueue = new CircleObjectQueue();
        int tempNumNodes = connectivityMatrix.getRows();


        // Initialize the queue
        tempVisitedArray[paraStartIndex] = true;
        resultString += paraStartIndex;
        tempQueue.enqueue(paraStartIndex);

        //Now visit the rest of the graph.
        int tempIndex;
        Integer tempInteger = (Integer) tempQueue.dequeue();
        while (tempInteger != null){
            tempIndex = tempInteger.intValue();

            //Enqueue all its unvisited neighbors.
            for (int i = 0; i < tempNumNodes; i++){
                if (tempVisitedArray[i]){
                    // Already visited.
                    continue;
                }
                if (connectivityMatrix.getData()[tempIndex][i] == 0) {
                    //Not directly connected.
                    continue;
                }
                tempVisitedArray[i] = true;
                resultString += i;
                tempQueue.enqueue(i);
            }

            //Take out one from the head.
            tempInteger = (Integer)tempQueue.dequeue();
        }
        return resultString;
    }

    /**
     * Judge connectivity
     * @param
     * @return
     */
    public boolean breadthTraversal(int paraStartIndex) {
        int tempNumNodes = connectivityMatrix.getRows();
        tempVisitedArray = new boolean[tempNumNodes];
        resultString = "";
        breadthFirstTraversal(paraStartIndex);

        for (int i = 0; i < tempNumNodes; i++){
            if (!tempVisitedArray[i]){
                breadthFirstTraversal(i);
                return false;
            }
        }
        return true;
    }


    public String depthFirstTraversal(int  paraStartIndex) {
        ObjectStack tempStack = new ObjectStack();

        int tempNumNodes = connectivityMatrix.getRows();
        tempVisitedArray = new boolean[tempNumNodes];

        tempVisitedArray[paraStartIndex] = true;
        resultString += paraStartIndex;
        tempStack.push(new Integer(paraStartIndex));
        System.out.println("Push " + paraStartIndex);
        System.out.println("Visited " + resultString);

        int tempIndex = paraStartIndex;
        int tempNext;
        Integer tempInteger;
        while (true) {
            tempNext = -1;
            // Find an unvisited neighbor and push
            for (int i = 0; i < tempNumNodes; i++) {
                if (tempVisitedArray[i]) {
                    continue; //Already visited.
                }

                if (connectivityMatrix.getData()[tempIndex][i] == 0) {
                    continue; //Not directly connected.
                }

                tempVisitedArray[i] = true;
                resultString += i;
                tempStack.push(new Integer(i));
                System.out.println("Push " + i);
                tempNext = i;

                break;
            }


            if (tempNext == -1) {
                //there is no neighbor node, pop
                tempInteger = (Integer) tempStack.pop();
                System.out.println("Pop " + tempInteger);
                if (tempStack.isEmpty()) {
                    //No unvisited neighbor。Backtracking to the last one stored in the stack
                    break;
                }else {
                    tempInteger = (Integer) tempStack.pop();
                    tempIndex = tempInteger.intValue();
                    tempStack.push(tempInteger);
                }
            } else {
                tempIndex = tempNext;
            }
        }
        return resultString;

    }

    public boolean depthTraversal(int paraStartIndex){
        int tempNumNodes = connectivityMatrix.getRows();
        tempVisitedArray = new boolean[tempNumNodes];
        resultString = "";
        depthFirstTraversal(paraStartIndex);

        for (int i = 0; i < tempNumNodes; i++){
            if (!tempVisitedArray[i]){
                depthFirstTraversal(i);
                return false;
            }
        }
        return true;
    }
    public static void depthFirstTraversalTest() {
        // Test an undirected graph.
        //int[][] tempMatrix = { { 0, 1, 1, 0 }, { 1, 0, 0, 1 }, { 1, 0, 0, 0}, { 0, 1, 0, 0} };
        int[][] tempMatrix = { { 0, 1, 1, 0 , 0}, { 1, 0, 0, 1, 0 }, { 1, 0, 0, 1, 0}, { 0, 1, 1, 0, 0}, { 0, 0, 0, 0, 0} };
        Graph tempGraph = new Graph(tempMatrix);
        System.out.println(tempGraph);

        String tempSequence = "";
        try {
            //tempSequence = tempGraph.depthFirstTraversal(0);
            tempGraph.depthTraversal(2);
        } catch (Exception ee) {
            System.out.println(ee);
        } // Of try.

        System.out.println("The depth first order of visit: " +  tempGraph.resultString);
    }

    public static void breadthFirstTraversalTest() {
        // Test an undirected graph.
        //int[][] tempMatrix = { { 0, 1, 1, 0 }, { 1, 0, 0, 1 }, { 1, 0, 0, 1}, { 0, 1, 1, 0} };
        //int[][] tempMatrix = { { 0, 1, 1, 0 , 0}, { 1, 0, 0, 1, 0 }, { 1, 0, 0, 1, 0}, { 0, 1, 1, 0, 0}, { 0, 0, 0, 0, 0} };
        int[][] tempMatrix = { { 0, 1, 1, 0 , 0, 0, 0}, { 1, 0, 0, 1, 0, 0, 0 }, { 1, 0, 0, 1, 0, 0, 0}, { 0, 1, 1, 0, 0, 0, 0}, { 0, 0, 0, 0, 0, 1, 1}, { 0, 0, 0, 0, 1, 0, 0}, { 0, 0, 0, 0, 0, 0, 0} };
        Graph tempGraph = new Graph(tempMatrix);
        System.out.println(tempGraph);

        String tempSequence = "";
        try {
            tempGraph.breadthTraversal(2);
            //tempSequence = tempGraph.breadthFirstTraversal(2);
        } catch (Exception ee) {
            System.out.println(ee.getMessage());
            return;
        }

        System.out.println("The breadth first order of visit: " + tempGraph.resultString);
    }

    public static void main(String[] args) {
        System.out.println("Hello!");
        Graph tempGraph = new Graph(3);
        System.out.println(tempGraph);

        // Unit test.
        getConnectivityTest();

        breadthFirstTraversalTest();

        depthFirstTraversalTest();
    }


}

  • 单元测试1(文章中给出的例子)
    在这里插入图片描述
    从0开始出发:
    在这里插入图片描述

  • 单元测试2
    在这里插入图片描述
    从0开始出发:
    在这里插入图片描述

  • 单元测试3
    从0开始:
    在这里插入图片描述
    在这里插入图片描述

3.总结

在对树或图遍历的时候,根据他们的结构,我们都需要保存访问的节点。

1.在广度遍历中借助了队列

在进行图的广度遍历可以结合树的层次遍历,先说树的层次遍历,它需要一层一层的遍历节点当第一层节点遍历完了,如何找到第二层节点?第二层是上一层的孩子节点,所以第一层访问后将要将节点保存起来,选择存储的结构可以是栈或队列。队列(先进先出)出栈是从左到右的顺序,这更符合我们的读写顺序,用栈(先进后出)来实现则出栈顺序就会很混乱,所以层次遍历使用队列。进一步,在对图的广度遍历,我们更愿意借助队列来实现遍历。

2.在深度优先遍历借助了栈。

在对树进行先序遍历时,我们访问完节点后,需要把节点保存,存储我们也可以选择栈和队列,若使用队列,因为队列特点先进先出,进队列顺序可以,但是在出队列时需要的结点在队尾。因此队列无法达到遍历的要求,但是栈先进后出更适合。进一步我们图的深度遍历会更先弄考虑的是栈。
列和栈特点可以在很多地方应用,例如逆向打印数据,顺序输入数据进入栈在输出时可以逆序打印。(例如Day26:: 二叉树深度遍历的栈实现 (前序和后序))

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/440995.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

Android 开发之核心技术点——性能优化篇(带面试题)~

性能优化对于Android开发的重要性非常大。随着Android设备的不断升级&#xff0c;用户对应用的要求也越来越高&#xff0c;包括应用的运行速度、响应速度、流畅度等方面。如果应用的性能不能满足用户的需求&#xff0c;很可能会导致用户流失、差评以及应用被卸载等情况。 另外…

boot-admin整合flowable官方editor-app进行BPMN2.0建模

boot-admin整合flowable官方editor-app源码进行BPMN2.0建模 正所谓百家争鸣、见仁见智、众说纷纭、各有千秋&#xff01;在工作流bpmn2.0可视化建模工具实现的细分领域&#xff0c;网上扑面而来的是 bpmn.js 这个渲染工具包和web建模器&#xff0c;而笔者却认为使用flowable官…

2023零基础快速跟上人工智能第一梯队

写在前面&#xff1a;有关人工智能学什么&#xff0c;怎么学&#xff0c;什么路线等一系列问题。我决定整理一套可行的规划路线&#xff0c;希望帮助准备入门的朋友们少走些弯路。 下面我会推荐一个比较快速可行的学习模板&#xff0c;并附上我认为比较好的学习资料。 新手不建…

git使用规范文档

git使用规范文档 Git使用规范流程图 开发人员操作步骤&#xff1a; 第一步&#xff1a;clone代码 在你的本地代码库进行从远程仓库clone代码操作&#xff08;100%表示clone完成&#xff09; 进入项目文件&#xff0c;右键Git Bash Here 切换到你所进行开发的分支上 拉取该分…

JavaSE学习进阶day05_02 常见的数据结构和List接口

第三章 数据结构&#xff08;掌握&#xff09; 3.1 数据结构介绍 数据结构 : 数据用什么样的方式组合在一起。 科班出身的同学我想你对数据结构一点也不陌生&#xff0c;不知道你记不记得&#xff0c;当时学习数据结构的逻辑结构中的集合时&#xff0c;只是简单了解它&#…

hackathon 复盘:niche 海外软件工具正确的方法 6 个步骤

上周末&#xff0c;去参加了北京思否 hackathon&#xff0c;两天时间内从脑暴 & 挖掘软件 IDEA -> Demo 研发路演&#xff0c;这次经历让我难忘。这里我的看法是每个开发者圈友&#xff0c;都应该去参加一次 hackathon ~ 做 niche 软件正确的方法 这边先说结论&#xf…

vmware下Ubuntu系统中安装vscode

文章目录 前言&#xff1a;在线下载&#xff1a;离线下载包&#xff1a;配置C/C环境 前言&#xff1a; 这篇博客是为后面交叉编译程序放到树莓派上运行做的准备。同时也是自己在装过程中的一个记录。 在线与离线安装的唯一不同就是获取安装包是在线下载还是别的地方拷贝过来以…

【数据结构】- 链表之单链表(中)

文章目录 前言一、单链表(中)1.1 头删1.2尾删1.2.1第一种方法&#xff1a;1.2.2第二种方法&#xff1a;1.2.3多因素考虑 二、完整版代码2.1 SList.h2.2 SList.c2.3 Test.c 总结 前言 千万不要放弃 最好的东西 总是压轴出场 本章是关于数据结构中的链表之单链表(中) 提示&#…

数据结构与算法基础(王卓)(26)线性表的查找(2):顺序查找(二分查找、分块查找)

二、折半查找&#xff08;二分或对分查找) 前置条件和前面一样 最开始根据PPT示(实)例写出的程序框架&#xff1a; 一开始&#xff1a; low&#xff1a;第一位 high&#xff1a;最后一位 mid&#xff1a;正中间 查找数小于mid&#xff1a; 把high移动到mid前面一位&#xff08;…

从0搭建Vue3组件库(四): 如何开发一个组件

本篇文章将介绍如何在组件库中开发一个组件,其中包括 如何本地实时调试组件如何让组件库支持全局引入如何在 setup 语法糖下给组件命名如何开发一个组件 目录结构 在packages目录下新建components和utils两个包,其中components就是我们组件存放的位置,而utils包则是存放一些…

观看js编程范式笔记(函数式编程)

js为什么鼓励函数式编程&#xff1f; JavaScript&#xff08;简称 JS&#xff09;是一种面向对象和函数式编程语言&#xff0c;但它在语言层面上更加鼓励函数式编程。以下是几个原因&#xff1a; 函数是一等公民&#xff1a;在 JavaScript 中&#xff0c;函数被视为一等公民&a…

HANA SDA连接外部数据库到BW的步骤

咱都知道&#xff0c;我们不能直接从BW连接到外部数据库。第一步得从HANA database通过SDA去建一个到外部DB的连接。 数据库连接好了&#xff0c;那么接下来别忘了&#xff0c;还得建一个源系统。 也就是说第一步&#xff0c;我们要用HANA SDA通过Linux ODBC driver去连接外部…

Vue3表格(Table)

Vue2表格&#xff08;Table&#xff09; 可自定义设置以下属性&#xff1a; 表格列的配置项&#xff08;columns&#xff09;&#xff0c;类型&#xff1a;Array<{title?: string, width?: number, dataIndex?: string, slot?: string}>&#xff0c;默认 [] 表格数…

史上最全面的苹果公司PMO的运作模式详解

01 苹果公司PMO的发展历程 1. 初期阶段&#xff1a; 在苹果公司刚创立的早期&#xff0c;没有明确的PMO组织。项目经理直接向CEO Steve Jobs汇报&#xff0c;项目管理在公司内部较为分散。 2. 1997年-2001年&#xff1a; 在这段时间内&#xff0c;苹果公司开始成立项目管理…

PasteSpider之关于字符串模板占位字符等的说明

PasteSpider中&#xff0c;构建&#xff0c;部署等都是通过命令执行的&#xff0c;为了更加的灵活&#xff0c;引入了不同的变量&#xff0c;以便适合不同的需求使用。 命令占位符 注&#xff01;&#xff01;&#xff01;&#xff0c;占位符的格式为{{对象.属性}},他们之间没有…

【LeetCode: 1691. 堆叠长方体的最大高度 | 暴力递归=>记忆化搜索=>动态规划】

&#x1f680; 算法题 &#x1f680; &#x1f332; 算法刷题专栏 | 面试必备算法 | 面试高频算法 &#x1f340; &#x1f332; 越难的东西,越要努力坚持&#xff0c;因为它具有很高的价值&#xff0c;算法就是这样✨ &#x1f332; 作者简介&#xff1a;硕风和炜&#xff0c;…

vue2+vue3——42+

vue2vue3——42 vue2 v-cloak指令【14:14】调网速 &#xff1a; no throttling 不让慢 &#xff1b; offline 断网JS 阻塞红色 外部JS &#xff1b; 绿色 网页核心 &#xff1b; 粉色 JS 脚本红色 外部JS 我要走不了&#xff0c; 谁都别想走 &#xff1a; 绿色 不可以渲染到页面…

【安全与风险】互联网协议漏洞

互联网协议漏洞 互联网基础设施TCP协议栈因特网协议&#xff08;IP&#xff09;IP路由IP协议功能(概述)问题:没有src IP认证用户数据报协议&#xff08;UDP&#xff09;传输控制协议 (TCP)TCP报头TCP(三向)握手基本安全问题数据包嗅听TCP连接欺骗随机初始TCP SNs 路由的漏洞Arp…

【OJ比赛日历】快周末了,不来一场比赛吗? #04.15-04.21 #17场

CompHub 实时聚合多平台的数据类(Kaggle、天池…)和OJ类(Leetcode、牛客…&#xff09;比赛。本账号同时会推送最新的比赛消息&#xff0c;欢迎关注&#xff01; 更多比赛信息见 CompHub主页 或 点击文末阅读原文 以下信息仅供参考&#xff0c;以比赛官网为准 目录 2023-04-15&…

openpnp - 顶部相机辅助光的选择

文章目录 openpnp - 顶部相机辅助光的选择概述折腾的过程简易灯板市售的环形灯(不带漫射板)市售的环形灯(不带漫射板) LED单色光调光控制器.市售的环形灯(带漫射板)市售的环形灯(带漫射板) 自己拆解(降低LED灯路数)END openpnp - 顶部相机辅助光的选择 概述 终于将顶部相机…