基于JAVA的深度优先遍历

10 篇文章 0 订阅
5 篇文章 0 订阅

算法分析课程作业(仅供参考)

基于栈的实现方式

源代码:

import java.util.Stack;

/**
 * @description: Depth first search algorithm
 * @author: Qing Zhang
 * @time: 09
 */
public class DFS {

    /**
     * @Description: Depth first search algorithm based on stack.
     * @Param: [paraGraph : Graph that need to be searched, paraNode : Node currently being traversed]
     * @return: java.lang.String
     */
    public static String depthFirstSearch(int[][] paraGraph, int paraNode) {
        Stack<Integer> tempStack = new Stack<>();
        boolean[] visited = new boolean[paraGraph.length];
        boolean flag = false;
        visited[paraNode] = true;
        tempStack.push(paraNode);
        String resString = "" + paraNode;
        int tempNode;
        while (!tempStack.isEmpty()) {
            tempNode = tempStack.peek();
            for (int i = 0; i < paraGraph.length; i++) {
                if (!visited[i] && paraGraph[tempNode][i] == 1) {
                    visited[i] = true;
                    tempStack.push(i);
                    resString += i;
                    flag = true;
                    break;
                }
            }
            if (!flag) {
                tempStack.pop();
            }
            flag = false;
        }
        return resString;
    }

    /**
     * @Description: Used to test depth-first traversal.
     * @Param: []
     * @return: void
     */
    public static void unitTestForDFS() {
        int[][] testGraph = new int[][]{
                {0, 1, 0, 1, 0, 0, 1},
                {1, 0, 0, 0, 1, 0, 0},
                {0, 0, 0, 1, 0, 1, 0},
                {1, 0, 1, 0, 0, 0, 0},
                {0, 1, 0, 0, 0, 0, 0},
                {0, 0, 1, 0, 0, 0, 0},
                {1, 0, 0, 0, 0, 0, 0}
        };

        // Depth-first traversal starting at each node.
        for (int i = 0; i < testGraph.length; i++) {
            String str = DFS.depthFirstSearch(testGraph, i);
            System.out.println("Use the " + (i + 1) + "-th node as the starting position");
            System.out.println(str);
        }
    }

    public static void main(String[] args) {
        DFS.unitTestForDFS();
    }
}

构造数据:
在这里插入图片描述

运行结果:

C:\Users\Administrator\.jdks\temurin-11.0.12-1\bin\java.exe "-javaagent:E:\IntelliJ IDEA 2020.1\lib\idea_rt.jar=55244:E:\IntelliJ IDEA 2020.1\bin" -Dfile.encoding=UTF-8 -classpath D:\JavaProject\JustForTest\out\production\JustForTest DFS
Use the 1-th node as the starting position
0143256
Use the 2-th node as the starting position
1032564
Use the 3-th node as the starting position
2301465
Use the 4-th node as the starting position
3014625
Use the 5-th node as the starting position
4103256
Use the 6-th node as the starting position
5230146
Use the 7-th node as the starting position
6014325

Process finished with exit code 0

基于递归的实现方式

源代码:

/**
 * @description: Depth first search algorithm based on recursion
 * @author: Qing Zhang
 * @time: 09
 */
public class DFS_Recursion {

    // Judge whether it has been traversed.
    private static boolean[] visited;

    /**
     * @Description: Depth first search algorithm based on recursion.
     * @Param: [paraGraph : Graph that need to be searched, paraNode : Node currently being traversed]
     * @return: java.lang.String
     */
    public static String depthFirstSearchByRecursion(int[][] paraGraph, int paraNode) {
        visited[paraNode] = true;
        String resString = "" + paraNode;
        for (int i = 0; i < paraGraph.length; i++) {
            if (!visited[i] && paraGraph[paraNode][i] == 1) {
                resString += depthFirstSearchByRecursion(paraGraph, i);
            }
        }
        return resString;
    }

    /**
     * @Description: Used to test depth-first traversal based on recursion.
     * @Param: []
     * @return: void
     */
    public static void unitTestForDFSByRecursion() {
        int[][] testGraph = new int[][]{
                {0, 1, 0, 1, 0, 0, 1},
                {1, 0, 0, 0, 1, 0, 0},
                {0, 0, 0, 1, 0, 1, 0},
                {1, 0, 1, 0, 0, 0, 0},
                {0, 1, 0, 0, 0, 0, 0},
                {0, 0, 1, 0, 0, 0, 0},
                {1, 0, 0, 0, 0, 0, 0}
        };

        // Depth-first traversal starting at each node.
        for (int i = 0; i < testGraph.length; i++) {
            visited = new boolean[testGraph.length];
            String str = DFS_Recursion.depthFirstSearchByRecursion(testGraph, i);
            System.out.println("Use the " + (i + 1) + "-th node as the starting position");
            System.out.println(str);
        }
    }

    public static void main(String[] args) {
        DFS_Recursion.unitTestForDFSByRecursion();
    }
}

构造数据:
在这里插入图片描述

运行结果:

C:\Users\Administrator\.jdks\temurin-11.0.12-1\bin\java.exe "-javaagent:E:\IntelliJ IDEA 2020.1\lib\idea_rt.jar=60437:E:\IntelliJ IDEA 2020.1\bin" -Dfile.encoding=UTF-8 -classpath D:\JavaProject\JustForTest\out\production\JustForTest DFS_Recursion
Use the 1-th node as the starting position
0143256
Use the 2-th node as the starting position
1032564
Use the 3-th node as the starting position
2301465
Use the 4-th node as the starting position
3014625
Use the 5-th node as the starting position
4103256
Use the 6-th node as the starting position
5230146
Use the 7-th node as the starting position
6014325

Process finished with exit code 0

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
有多种方法可以实现树的深度优先遍历。一种常见的方法是使用递归。通过递归地访问左子树和右子树,可以实现深度优先遍历。以下是一个使用递归实现深度优先遍历Java代码: ``` public void dfs(TreeNode node) { if (node == null) { return;<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* [java有序二叉树的深度优先遍历和广度优先遍历](https://blog.csdn.net/m566666/article/details/122280365)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT0_1"}}] [.reference_item style="max-width: 33.333333333333336%"] - *2* [深度优先遍历和广度优先遍历(Java)](https://blog.csdn.net/m0_46628950/article/details/125830847)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT0_1"}}] [.reference_item style="max-width: 33.333333333333336%"] - *3* [基于Java深度优先遍历(DFS)和广度优先遍历(BFS)](https://blog.csdn.net/Robin_Ywj/article/details/121791796)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT0_1"}}] [.reference_item style="max-width: 33.333333333333336%"] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值