当前位置:

首页 > 编程开发 > 双向搜索算法Java实现与路径解析

双向搜索算法Java实现与路径解析

本文旨在帮助开发者理解和实现双向路径搜索算法。通过分析常见的实现错误,并提供改进方案,本文将详细介绍如何使用Java构建高效的双向搜索树,并从搜索树中正确提取完整的路径信息,最终实现从起点到终点的完整路径搜索。

本文目录

    双向路径搜索算法的Java实现及路径构建详解

    本文旨在帮助开发者理解和实现双向路径搜索算法。通过分析常见的实现错误,并提供改进方案,本文将详细介绍如何使用Java构建高效的双向搜索树,并从搜索树中正确提取完整的路径信息,最终实现从起点到终点的完整路径搜索。

    理解双向路径搜索

    双向路径搜索是一种在图中寻找从起点到终点路径的优化算法。它同时从起点和终点开始搜索,当两个搜索方向相遇时,就找到了连接起点和终点的路径。相比于单向搜索,双向搜索通常能够更快地找到目标路径,尤其是在搜索空间较大的情况下。

    常见的实现错误

    原始代码中存在一些关键问题,导致无法正确构建和使用双向搜索树:

    1. 共享搜索树: 使用单一的 searchTreeParentByChild 存储两个方向的搜索结果是不正确的。因为两个方向的路径是从不同的起点构建,并且方向相反。使用同一个树结构无法区分路径的方向。
    2. 路径构建方向错误: searchTreeParentByChild 只能从子节点追溯到父节点,而无法反向查找。这导致无法从相遇点正确构建从起点到终点的完整路径。
    3. containsValue 的错误使用: 在 curEnd 的循环中,使用 searchTreeParentByChild.containsValue(e.to()) 来判断顶点是否被访问过是错误的。containsValue 用于检查 Map 中是否存在特定的值,而不是键。正确的做法是使用 containsKey(e.to())。

    改进的实现方案

    为了解决上述问题,我们需要进行以下改进:

    1. 使用两个独立的搜索树: 为从起点和终点开始的搜索分别创建 searchTreeParentByChildFromStart 和 searchTreeParentByChildFromEnd。这两个 Map 分别存储从起点和从终点开始的搜索树。
    2. 正确的顶点访问检查: 使用 containsKey() 方法检查顶点是否已经被访问过。
    3. 完整路径构建: 当两个搜索方向相遇时,需要分别从相遇点向起点和终点追溯路径,然后将两条路径合并。

    以下是改进后的 Java 代码示例:

    import java.util.*;
    
    public class BidirectionalSearch {
    
        private final Graph graph;
        private final Map searchTreeParentByChildFromStart = new HashMap<>();
        private final Map searchTreeParentByChildFromEnd = new HashMap<>();
    
        public BidirectionalSearch(Graph graph) {
            this.graph = graph;
        }
    
        public BidirectionalSearch buildSearchTree(Vertex start, Vertex end) {
            if (!graph.vertices().containsAll(List.of(start, end)))
                throw new IllegalArgumentException("start or stop vertices not from this graph");
    
            if (start.equals(end))
                return this;
    
            searchTreeParentByChildFromStart.clear();
            searchTreeParentByChildFromEnd.clear();
    
            Queue unvisitedVertexQueueFromStart = new ArrayDeque<>();
            Queue unvisitedVertexQueueFromEnd = new ArrayDeque<>();
    
            unvisitedVertexQueueFromStart.add(start);
            unvisitedVertexQueueFromEnd.add(end);
    
            searchTreeParentByChildFromStart.put(start, null);
            searchTreeParentByChildFromEnd.put(end, null);
    
            Vertex intersectionVertex = null;
    
            while (!unvisitedVertexQueueFromStart.isEmpty() && !unvisitedVertexQueueFromEnd.isEmpty()) {
                Vertex curStart = unvisitedVertexQueueFromStart.poll();
    
                for (Edge e : curStart.edges()) {
                    Vertex neighbor = e.to();
                    if (!searchTreeParentByChildFromStart.containsKey(neighbor)) {
                        searchTreeParentByChildFromStart.put(neighbor, curStart);
                        unvisitedVertexQueueFromStart.add(neighbor);
    
                        if (searchTreeParentByChildFromEnd.containsKey(neighbor)) {
                            intersectionVertex = neighbor;
                            break; // Found intersection
                        }
                    }
                }
    
                if (intersectionVertex != null) break;
    
    
                Vertex curEnd = unvisitedVertexQueueFromEnd.poll();
    
                for (Edge e : curEnd.edges()) {
                    Vertex neighbor = e.to();
                    if (!searchTreeParentByChildFromEnd.containsKey(neighbor)) {
                        searchTreeParentByChildFromEnd.put(neighbor, curEnd);
                        unvisitedVertexQueueFromEnd.add(neighbor);
    
                        if (searchTreeParentByChildFromStart.containsKey(neighbor)) {
                            intersectionVertex = neighbor;
                            break; // Found intersection
                        }
                    }
                }
    
                if (intersectionVertex != null) break;
    
            }
    
            return this;
        }
    
        public List getPath(Vertex start, Vertex end) {
            buildSearchTree(start, end);
            Vertex intersection = findIntersection(start, end);
    
            if (intersection == null) {
                return Collections.emptyList(); // No path found
            }
    
            List pathToIntersectionFromStart = buildPath(searchTreeParentByChildFromStart, intersection);
            List pathToIntersectionFromEnd = buildPath(searchTreeParentByChildFromEnd, intersection);
    
            Collections.reverse(pathToIntersectionFromEnd); // Reverse the end path
    
            List fullPath = new ArrayList<>();
            fullPath.addAll(pathToIntersectionFromStart);
            fullPath.addAll(pathToIntersectionFromEnd.subList(1, pathToIntersectionFromEnd.size())); // Avoid duplicate intersection vertex
    
            return fullPath;
        }
    
        private Vertex findIntersection(Vertex start, Vertex end) {
            for (Vertex vertex : searchTreeParentByChildFromStart.keySet()) {
                if (searchTreeParentByChildFromEnd.containsKey(vertex)) {
                    return vertex;
                }
            }
            return null;
        }
    
        private List buildPath(Map searchTree, Vertex intersection) {
            List path = new LinkedList<>();
            Vertex current = intersection;
    
            while (current != null) {
                path.add(0, current); // Add to the beginning to reverse the path
                current = searchTree.get(current);
            }
    
            return path;
        }
    
        // Example Graph, Vertex and Edge classes (replace with your actual implementations)
        static class Graph {
            private final Set vertices = new HashSet<>();
    
            public void addVertex(Vertex vertex) {
                vertices.add(vertex);
            }
    
            public Set vertices() {
                return vertices;
            }
        }
    
        static class Vertex {
            private final String name;
            private final List edges = new ArrayList<>();
    
            public Vertex(String name) {
                this.name = name;
            }
    
            public String getName() {
                return name;
            }
    
            public void addEdge(Edge edge) {
                edges.add(edge);
            }
    
            public List edges() {
                return edges;
            }
    
            @Override
            public boolean equals(Object o) {
                if (this == o) return true;
                if (o == null || getClass() != o.getClass()) return false;
                Vertex vertex = (Vertex) o;
                return Objects.equals(name, vertex.name);
            }
    
            @Override
            public int hashCode() {
                return Objects.hash(name);
            }
        }
    
        static class Edge {
            private final Vertex from;
            private final Vertex to;
            private final int weight;
    
            public Edge(Vertex from, Vertex to, int weight) {
                this.from = from;
                this.to = to;
                this.weight = weight;
            }
    
            public Vertex to() {
                return to;
            }
        }
    
        public static void main(String[] args) {
            // Example Usage
            Graph graph = new Graph();
            Vertex start = new Vertex("A");
            Vertex b = new Vertex("B");
            Vertex c = new Vertex("C");
            Vertex end = new Vertex("D");
    
            graph.addVertex(start);
            graph.addVertex(b);
            graph.addVertex(c);
            graph.addVertex(end);
    
            start.addEdge(new Edge(start, b, 1));
            b.addEdge(new Edge(b, c, 1));
            c.addEdge(new Edge(c, end, 1));
            end.addEdge(new Edge(end, c, 1));
    
            BidirectionalSearch search = new BidirectionalSearch(graph);
            List path = search.getPath(start, end);
    
            if (!path.isEmpty()) {
                System.out.println("Path found: ");
                for (Vertex vertex : path) {
                    System.out.print(vertex.getName() + " ");
                }
                System.out.println();
            } else {
                System.out.println("No path found.");
            }
        }
    }

    代码解释:

    • searchTreeParentByChildFromStart 和 searchTreeParentByChildFromEnd:分别存储从起点和终点开始的搜索树,记录每个节点的父节点。
    • getPath(Vertex start, Vertex end): 构建搜索树,找到两个方向相遇的顶点,然后分别构建从起点到相遇点和从终点到相遇点的路径,最后合并这两条路径。
    • buildPath(Map searchTree, Vertex intersection): 从相遇点开始,通过搜索树向上追溯到起点或终点,构建单向路径。
    • findIntersection(Vertex start, Vertex end): 找到两个搜索树的相交顶点。

    注意事项

    • 图的表示: 上述代码示例中使用了简单的 Graph, Vertex 和 Edge 类。在实际应用中,你需要根据你的图的结构来调整这些类的实现。
    • 性能优化: 双向搜索的性能高度依赖于图的结构。在某些情况下,单向搜索可能更有效。可以考虑使用启发式函数来指导搜索方向,进一步优化性能。
    • 路径权重: 上述代码只关注是否存在路径,没有考虑路径的权重。如果需要找到最短路径,需要修改代码,在搜索过程中维护每个节点的距离信息,并使用合适的优先队列(例如,使用 PriorityQueue)来选择下一个要访问的节点。
    • 环路处理: 在构建搜索树时,需要小心处理环路,避免无限循环。可以使用一个额外的 visited 集合来记录已经访问过的节点。

    总结

    双向路径搜索是一种强大的图搜索算法,可以有效地找到起点和终点之间的路径。 通过使用两个独立的搜索树,并正确地构建和合并路径,可以避免常见的实现错误,获得正确的搜索结果。 在实际应用中,需要根据图的结构和性能需求,对算法进行适当的优化。

    本站声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系bd@zhengruan.com
    作者最新文章
    编程开发
    相关文章 更多
    QQ影音怎么加速播放视频课程
    QQ影音怎么加速播放视频课程

    播放时右键选播放速度,或点控制条倍速,1.25 到 1.5 倍看课最舒服;公式代码类内容别超过 1.25 倍。

    企业微信创建企业提示失败怎么办 实名与填写检查
    企业微信创建企业提示失败怎么办 实名与填写检查

    先看提示属于哪类:名称占用就加后缀,实名不一致就重填本人信息,证件不清晰就重拍。统一社会信用代码逐位核对,连续三次失败别改材料重投,直接联系客服人工核。

    Modern Web Guidance 的 legacy-scan 反转建议应该怎样判断?
    Modern Web Guidance 的 legacy-scan 反转建议应该怎样判断?

    说明源码提交对字符串、生成器和数组的识别边界,以及扫描命令与发行包核验限制。

    Codex 0.170.0 正式版的语音与连接更新,适用范围有哪些限制?
    Codex 0.170.0 正式版的语音与连接更新,适用范围有哪些限制?

    0.170.0 的语音更新限于终端通话协商能力的明确新增,同名工具服务器跨环境支持仍标注实验性质;连接部分则修复大请求回退、认证竞态和云端重连等具体问题。这份正式版公告不足以证明所有账户、所有客户端都已具备完整语音功能。

    Hy4 flash 三种权重怎么选,安装和授权要注意哪些条件?
    Hy4 flash 三种权重怎么选,安装和授权要注意哪些条件?

    了解Hy4 flash、FP8与base的适用任务,阅读官方安装及图文代码,并核对资源和MaaS许可条件。

    OpenAI Python SDK 3.55.0 升级看点:Live MCP 服务配置与预算接口变化
    OpenAI Python SDK 3.55.0 升级看点:Live MCP 服务配置与预算接口变化

    OpenAI Python SDK 3.55.0 升级看点:Live MCP 服务配置与预算接口变化。说明已核实的更新范围、类型兼容性和本地版本确认方法。

    OpenAI Java SDK 4.108.0 的两项新增能力适合哪些项目?
    OpenAI Java SDK 4.108.0 的两项新增能力适合哪些项目?

    OpenAI Java SDK 4.108.0 面向 Live MCP 工具接入与 Managed Agents 预算状态处理,说明新增模型、事件含义、正式发布范围和适用限制。

    Free Claude Code 6.19.37 如何兼顾网页搜索与普通工具调用?
    Free Claude Code 6.19.37 如何兼顾网页搜索与普通工具调用?

    Free Claude Code 6.19.37 在自动搜索时保留客户端工具及选择条件,代理执行搜索后仍返回普通调用。说明适用场景、历史信息保留、请求约束与第三方项目的版本边界。

    Google GenAI Go SDK 1.78.0 的 v1beta 配置优先级怎样判断?
    Google GenAI Go SDK 1.78.0 的 v1beta 配置优先级怎样判断?

    Google GenAI Go SDK 1.78.0 将 Gemini Developer API 默认改为 v1,可用 HTTPOptions.APIVersion 或环境变量保留 v1beta,Vertex AI 默认值不变。

    Google GenAI SDK 3.5.0实时交互值得哪些项目升级评估?
    Google GenAI SDK 3.5.0实时交互值得哪些项目升级评估?

    解释实验性实时支持、环境检查与生产评估中需要验证的条件。

    查看更多
    精品专题 更多
    装机必备
    装机必备

    正软商城装机必备专区,精选办公、浏览器、安全防护、影音播放、压缩解压、设计创作和系统工具等电脑常用正版软件,帮助用户快速完成新电脑软件配置。

    Windows
    Windows

    正软商城Windows软件专区,汇集适用于Windows电脑的办公、设计、安全防护、影音播放、开发工具和系统优化软件,提供软件介绍、系统要求、正版授权及购买下载服务。

    PDF教程
    PDF教程

    正软商城PDF教程频道提供PDF编辑、转换、合并、拆分、压缩及格式处理方法,同时介绍常用PDF软件和工具的使用技巧。

    Mac软件 更多
    讯飞智作 网页版
    讯飞智作 网页版
    Windows/ macOS/ Linux

    讯飞智作是一款基于语音合成技术、虚拟人驱动技术与数字人形象声音构建能力的 AI 数字人音视频创作平台。

    火山引擎 网页版
    火山引擎 网页版
    Windows/ macOS/ Linux

    火山引擎是字节跳动旗下企业级云与AI服务平台。聚焦大模型核心能力,依托字节自研豆包多模态大模型,凭借火山方舟一站式平台,提供模型精调、推理部署、智能应用搭建等全链路服务,结合高性能AI算力,助力各行业快速落地大模型数字化与智能化应用。

    Aperty macOS版
    Aperty macOS版
    macOS

    Aperty 是 Skylum 推出的 AI 人像修图软件,支持自然肤质修饰、瑕疵处理、面部与身体调整、预设及批量同步。

    WINDOWS 更多
    讯飞智作 网页版
    讯飞智作 网页版
    Windows/ macOS/ Linux

    讯飞智作是一款基于语音合成技术、虚拟人驱动技术与数字人形象声音构建能力的 AI 数字人音视频创作平台。

    火山引擎 网页版
    火山引擎 网页版
    Windows/ macOS/ Linux

    火山引擎是字节跳动旗下企业级云与AI服务平台。聚焦大模型核心能力,依托字节自研豆包多模态大模型,凭借火山方舟一站式平台,提供模型精调、推理部署、智能应用搭建等全链路服务,结合高性能AI算力,助力各行业快速落地大模型数字化与智能化应用。

    PixTV 网页版
    PixTV 网页版
    Windows

    PixTV 是一款在浏览器中使用的 AI 视觉内容创作平台,提供图片、视频、音频、文字生成、AI 分镜、局部重绘、提示词反推和无限画布等工具,适合短剧、漫剧、广告及社交媒体内容制作。