【Spring Boot】什么是深度优先遍历与广度优先遍历?用Spring Boot项目举例说明。

深度优先遍历(Depth First Search,DFS)和广度优先遍历(Breadth First Search,BFS)是图的遍历算法。其中,深度优先遍历从某个起始点开始,先访问一个节点,然后跳到它的一个相邻节点继续遍历,直到没有未遍历的节点,此时回溯到上一个节点,继续遍历其他的相邻节点。而广度优先遍历则是从某个起始点开始,依次遍历该节点的所有相邻节点,然后再依次遍历这些相邻节点的相邻节点,直到遍历完图中所有节点。

以Spring Boot项目中的REST API接口为例,可以通过遍历接口中的URI路径,实现DFS和BFS算法。具体实现可以在Spring Boot的控制器类中编写遍历代码,如下所示:

复制代码

java

复制代码
// DFS遍历实现`
@GetMapping("/dfs")
public List<String> dfs() {
    List<String> result = new ArrayList<String>();
    Stack<String> stack = new Stack<String>();
    stack.push("/");
    while (!stack.empty()) {
        String path = stack.pop();
        result.add(path);
        String[] subs = getSubPaths(path); // 获取当前路径的子路径
        for (String sub : subs) {
            stack.push(sub);
        }
    }
    return result;
}

`// BFS遍历实现`
@GetMapping("/bfs")
public List<String> bfs() {
    List<String> result = new ArrayList<String>();
    Queue<String> queue = new LinkedList<String>();
    queue.offer("/");
    while (!queue.isEmpty()) {
        String path = queue.poll();
        result.add(path);
        String[] subs = getSubPaths(path); // 获取当前路径的子路径
        for (String sub : subs) {
            queue.offer(sub);
        }
    }
    return result;
}

`// 获取路径的子路径`
private String[] getSubPaths(String path) {
    // 从Spring MVC的RequestMappingHandlerMapping中获取当前路径的所有子路径
    RequestMappingHandlerMapping handlerMapping = applicationContext.getBean(RequestMappingHandlerMapping.class);
    Map<RequestMappingInfo, HandlerMethod> map = handlerMapping.getHandlerMethods();
    Set<String> subs = new HashSet<String>();
    for (RequestMappingInfo info : map.keySet()) {
        String pattern = info.getPatternsCondition().getPatterns().iterator().next();
        if (pattern.startsWith(path) && !pattern.equals(path)) {
            int index = pattern.indexOf("/", path.length() + 1);
            if (index > -1) {
                subs.add(pattern.substring(0, index + 1));
            } else {
                subs.add(pattern);
            }
        }
    }
    return subs.toArray(new String[subs.size()]);
}
`

以上代码中,getSubPaths()方法使用Spring MVC的RequestMappingHandlerMapping获取所有的REST API接口路径,并过滤出当前路径的子路径。DFS遍历使用栈来实现,BFS遍历使用队列来实现。当遍历完成后,返回遍历得到的路径列表。这样,就可以使用REST API接口来演示DFS和BFS算法的实现了。

相关推荐
铉铉这波能秀12 分钟前
LeetCode Hot100数据结构背景知识之字典(Dictionary)Python2026新版
数据结构·python·算法·leetcode·字典·dictionary
蜡笔小马21 分钟前
10.Boost.Geometry R-tree 空间索引详解
开发语言·c++·算法·r-tree
唐梓航-求职中29 分钟前
编程-技术-算法-leetcode-288. 单词的唯一缩写
算法·leetcode·c#
仟濹31 分钟前
【算法打卡day3 | 2026-02-08 周日 | 算法: BFS】3_卡码网99_计数孤岛_BFS | 4_卡码网100_最大岛屿的面积DFS
算法·深度优先·宽度优先
Ll130452529835 分钟前
Leetcode二叉树part4
算法·leetcode·职场和发展
颜酱44 分钟前
二叉树遍历思维实战
javascript·后端·算法
宝贝儿好1 小时前
第二章: 图像处理基本操作
算法
小陈phd1 小时前
多模态大模型学习笔记(二)——机器学习十大经典算法:一张表看懂分类 / 回归 / 聚类 / 降维
学习·算法·机器学习
@––––––1 小时前
力扣hot100—系列4-贪心算法
算法·leetcode·贪心算法
CoovallyAIHub1 小时前
让本地知识引导AI追踪社区变迁,让AI真正理解社会现象
深度学习·算法·计算机视觉