您的位置:首页 > 其它

使用DFS求任意两点的所有路径

2016-04-07 14:51 399 查看
先上代码:

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


  

  
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: