zoukankan      html  css  js  c++  java
  • 使用DFS求任意两点的所有路径

    先上代码:

       public static void findAllPaths(Integer nodeId,Integer targetNodeId, Map<Integer,ArrayList<Integer>> reachMap) {
                for (Integer nextNode : reachMap.get(nodeId)) {
                    if (nextNode.equals(targetNodeId)) {
                        Stack temp = new Stack();
                        for (Integer node1 : connectionPath) {
                            temp.add(node1);
                        }
                        temp.push(demandRouterArray[1]);
                        temp.add(0, demandRouterArray[0]);
                        connectionPaths.add(temp);
                    } else if (!connectionPath.contains(nextNode)) {
                        connectionPath.push(nextNode);
                        findAllPaths(nextNode, targetNodeId,reachMap);
                        connectionPath.pop();
                    }
                }
        }

    1)reachMap的key是图中一个节点的id,而对应的value是列表形式,存储了这个节点可以直接到达的所有节点。其实,reachMap就是图的邻接表存储形式。

    2)搜索得到的一条路径存储在connectionPath中,使用Stack实现:

     static Stack<Integer> connectionPath=new Stack();
    

    3)所有的路径存储在connectionPaths中,是以Stack为元素的列表:

     static List<Stack> connectionPaths=new ArrayList<>();
    

      

      

  • 相关阅读:
    自定义转化
    asp.net JSON(一)
    做一个会偷懒的码农
    活动和监视器
    linq 分组求和
    sql语句查询列的说明
    chartControl
    LayOutControl
    sql 给表结构增加说明
    我的单件模式
  • 原文地址:https://www.cnblogs.com/lz3018/p/5363570.html
Copyright © 2011-2022 走看看