【发布时间】:2020-03-29 20:26:23
【问题描述】:
我正在尝试以图形形式在特殊数据结构中实现算法。我的目标是获取从叶子(目标元素)到根的所有路径。 图表如下图所示。
【问题讨论】:
标签: java algorithm data-structures graph
我正在尝试以图形形式在特殊数据结构中实现算法。我的目标是获取从叶子(目标元素)到根的所有路径。 图表如下图所示。
【问题讨论】:
标签: java algorithm data-structures graph
我们需要记住我们拥有的所有路径,以便以图表上的所有不同方式遍历,因此只有状态列表是不够的,我们需要一个路径列表。对于每条路径,如果它有一个父级,我们会将其加长一个,如果它有两个或更多,我们将复制此列表并将父级添加到每个路径。
好吧,我不擅长 Java,我不能运行这段代码,所以我不能保证它会运行,但算法没问题。
public static List<ARGState> getAllErrorStatesReversed(ReachedSet reachedSet) {
ARGState pIsStart =
AbstractStates.extractStateByType(reachedSet.getFirstState(), ARGState.class);
ARGState pEnd = targetStates.get(0);
List<List<ARGState>> results = new ArrayList<>();
List<List<ARGState>> paths = new ArrayList<>();
paths.add(new ArrayList<ARGState>(pEnd));
// This is assuming from each node there is a way to go to the start
// Go on until all the paths got the the start
while (!paths.empty()) {
// Expand the last path on your list
List<ARGState> curPath = paths.remove(paths.size() - 1);
// If there is no more to expand - add this path and continue
if (curPath.get(curPath.size() - 1) == pIsStart) {
results.append(curPath);
continue;
}
// Expand the path
Iterator<ARGState> parents = curPath.get(curPath.size() - 1).getParents().iterator();
// Add all parents
while (parentElement.hasNext()) {
ARGState parentElement = parents.next();
List<ARGState> tmp = new ArrayList<ARGState>(List.copyOf(curPath));
tmp.add(parentElement);
paths.add(tmp);
}
}
return results;
}
希望你能理解,多多欢迎提问。
祝你好运
【讨论】:
[id:0,Parents[]],[id:0,Parents[]],[id:0,Parents[]] 所以只有第一个元素的列表。 :(
E和V这两个术语的时间复杂度,因为算法是BFS,它是一个图算法。通常BFS的时间复杂度是O(E + V),但现在我们需要将所有不同的路径O(E*V)保存在复杂度中。