使用DFS求任意两点的所有路径
生活随笔
收集整理的這篇文章主要介紹了
使用DFS求任意两点的所有路径
小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
先上代碼:
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是圖中一個(gè)節(jié)點(diǎn)的id,而對(duì)應(yīng)的value是列表形式,存儲(chǔ)了這個(gè)節(jié)點(diǎn)可以直接到達(dá)的所有節(jié)點(diǎn)。其實(shí),reachMap就是圖的鄰接表存儲(chǔ)形式。
2)搜索得到的一條路徑存儲(chǔ)在connectionPath中,使用Stack實(shí)現(xiàn):
static Stack<Integer> connectionPath=new Stack();3)所有的路徑存儲(chǔ)在connectionPaths中,是以Stack為元素的列表:
static List<Stack> connectionPaths=new ArrayList<>();
轉(zhuǎn)載于:https://www.cnblogs.com/lz3018/p/5363570.html
總結(jié)
以上是生活随笔為你收集整理的使用DFS求任意两点的所有路径的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 怎样利用好单片机上的存储器资源来实现OD
- 下一篇: 160407、java实现多线程同步