我有一个存储在 Map 数据结构中的有向图,其中键是节点的 ID
[value]是key节点所指向的节点的nodeId数组。
Map<String, String[]> map = new HashMap<String, String[]>();
map.put("1", new String[] {"2", "5"});
map.put("2", new String[] {"3"});
map.put("3", new String[] {"4"});
map.put("4", new String[] {"4"});
map.put("5", new String[] {"5", "9"});
map.put("6", new String[] {"5"});
map.put("7", new String[] {"6"});
map.put("8", new String[] {"6"});
map.put("9", new String[] {"10"});
map.put("10", new String[] {"5"});
map.put("11", new String[] {"11"});
我编写了一个递归搜索算法,试图找到图中的圆圈。
Set<String> nodes = map.keySet();
for(String node : nodes) {
List<String> forbiddens = new ArrayList<>(); // This list stores the touched nodes, during the process.
forbiddens.add(node);
recursiveSearch(node, forbiddens);
}
该函数由上面的代码调用。
private void recursiveSearch(String nodeId, List<String> forbiddens) {
String[] neighbours = map.get(nodeId); // The given node's neighbours
for(String neighbour : neighbours) {
for(String forbidden : forbiddens) {
if(neighbour.equals(forbidden)) {
ways.add( getClone(forbidden) ); //getClone returns the copy of a given List, "ways" is a List<List<String>> which contains the lists of paths which are leading to a circle in the graph
return;
}
}
forbiddens.add(neighbour);
recursiveSearch(neighbour, forbiddens);
forbiddens.remove(neighbour);
}
}
有些路径包含我想删除的额外节点(不在圆圈中)。
我想请求帮助从“方式”列表中选择节点以获得圆的实际节点。
这个算法能找到图中的所有圆圈吗?