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<>();
    

      

      

  • 相关阅读:
    洛谷 1736 创意吃鱼法
    有多重限制的背包
    洛谷 1417 烹调方案
    2008 noip 传纸条
    环形石子合并 洛谷 1880 && hdu 3506 Monkey Party
    洛谷 1282 多米诺骨牌
    (金明的预算方案)依赖性的背包
    分组背包问题
    混合背包问题
    多重背包问题
  • 原文地址:https://www.cnblogs.com/lz3018/p/5363570.html
Copyright © 2011-2022 走看看