【问题标题】:Backtrace all paths possible from goal to the start point回溯从目标到起点的所有可能路径
【发布时间】:2021-03-15 16:26:32
【问题描述】:

有一个图 Map<Integer, List<Integer>> 的表示,其中键值是一个顶点,它有一个我们可以获得的其他顶点的列表。地图可能更大,列表可能是n size。数字 1 代表起始顶点,地图中最大的关键数字代表一个目标。

有没有办法循环并收集从目标到开始的所有可用路径组合的路径?

例子:

{ 2=[1], 3=[1], 4=[1], 5=[4, 2], 6=[4], 7=[1], 8=[7, 2], 9=[7, 3, 8] }

目标是 9,开始是 1,所以输出 List<List<Integer>> 应该是这样的:

[ [9, 7, 1], [9, 3, 1], [9, 8, 7, 1], [9, 8, 2, 1] ]

或不包括 1

[ [9, 7], [9, 3], [9, 8, 7], [9, 8, 2] ]

我的方法只取列表中的第一个元素

parentNodes 是Map<Integer, List<Integer>>

List<Integer> path = new ArrayList<>();
List<Integer> nodes = Collections.singletonList(goal);
while(nodes != null && nodes.size() > 0) {
        if (nodes.size() > 1) {
            if (nodes.get(0) != goal || nodes.get(1) != goal) {
                shortestPath.add(nodes.get(0));
                System.out.println(shortestPath);
            }
        } else {
            path.add(nodes.get(0));
        }
        nodes = parentNodes.get(nodes.get(0));

    }
    Collections.reverse(path);

输出是List&lt;Integer&gt; [9, 7] 或反向[7, 9] 这是最短路径之一

【问题讨论】:

  • 请附上您为解决问题而编写的代码。

标签: java algorithm dictionary graph


【解决方案1】:

您的目标可以通过最大顶点的 dfs 来实现。您需要存储路径而不访问路径中已经存在的任何顶点。详解here。 您只需将ArrayList&lt;Integer&gt;[] adjList; 更改为Map&lt;Integer, List&lt;Integer&gt;&gt; adjList;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-01
    • 1970-01-01
    相关资源
    最近更新 更多