【发布时间】: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<Integer> [9, 7] 或反向[7, 9] 这是最短路径之一
【问题讨论】:
-
请附上您为解决问题而编写的代码。
标签: java algorithm dictionary graph