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

  

  

posted @ 2016-04-07 14:51  lz3018  阅读(1391)  评论(0编辑  收藏  举报