检测图中的所有圆圈

tyu*_*tyi 5 java geometry graph graph-algorithm

我有一个存储在 Map 数据结构中的有向图,其中键是节点的 ID,[value] 是键节点指向的节点的 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"});
Run Code Online (Sandbox Code Playgroud)

我写了一个递归搜索算法,试图在图中定位圆。

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);
    }
Run Code Online (Sandbox Code Playgroud)

该函数由上面的代码调用。

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);
    }
}
Run Code Online (Sandbox Code Playgroud)

一些路径包含我想摆脱的额外节点(不在圆圈中)。我想寻求帮助从“方式”列表中选择节点以获取圆圈的实际节点。

这个算法能找到图中的所有圆圈吗?