有向圖:
:
找出 途中 從 A 到 F 一共有多少中走法, 包含的閉環 有哪些
構思:
遍歷前 先準備一個 list 用來存放當前路徑,
從A開始 先找到B ,B找到D, D 到F, 此時 F爲所找目標節點, 此時算是找到一條路徑, 此時路徑爲 A ,B,D,F
接下來 從 F 返回上一層 D 再找D 的另一個節點 C ,C有兩個子節點, 隨便選一個 B, 此時 當前路徑中存在一個B,重複了, 所以此處是一個環, 然後返回上一級C 再從C到 E E到F , 此時路徑爲 A ,B,D,C,E,F
再依次返回, 每上一層 都遍歷找沒有被訪問過的子節點, 直到訪問結束.
(如果看不明白的童鞋還是多跑幾次代碼 ,然後找規律吧.這個確實不太好解釋哈)
其中用到遞歸
上代碼:
/**
* @Annotion: 節點實體,一個實體對應的是一條線,鏈接兩個節點
* @ClassName: Node
* @Author:
* @Date: 2019/9/29 10:11
* @Version: 1.0
*/
public class Node {
/**上游節點*/
private String source;
/**下游節點*/
private String target;
public Node(String source, String target) {
this.source = source;
this.target = target;
}
public String getSource() {
return source;
}
public void setSource(String source) {
this.source = source;
}
public String getTarget() {
return target;
}
public void setTarget(String target) {
this.target = target;
}
}
/**
* @Annotion: 從 一個點 到另一個點所有路徑走法 ,並輸出環
* @ClassName: TwoPointsPath
* @Author:
* @Date: 2019/9/29 9:54
* @Version: 1.0
*/
public class PointsPath {
/**當前路徑*/
private static List<String> nowPath = new ArrayList<>();
/**
*
* @param nodeList
* @param source 起始節點
* @param target 目標節點
*/
public static void findAllPath(List<Node> nodeList,String source,String target){
if(nowPath.contains(source)){
System.out.println("這是一個環:"+nowPath);
nowPath.remove(nowPath.size()-1);
return;
}
for(int i = 0 ;i<nodeList.size();i++){
Node node = nodeList.get(i);
if(node.getSource().equals(source)){
nowPath.add(node.getSource());
if(node.getTarget().equals(target)){
nowPath.add(node.getTarget());
System.out.println("這是一條路徑:"+nowPath);
/*因爲添加了終點路徑,所以要返回兩次*/
nowPath.remove(nowPath.size()-1);
nowPath.remove(nowPath.size()-1);
/*已經找到路徑,返回上層找其他路徑*/
continue;
}
findAllPath(nodeList,node.getTarget(),target );
}
}
/*如果找不到下個節點,返回上層*/
if(nowPath.size()>0){
nowPath.remove(nowPath.size()-1);
}
}
/**
* 測試
*/
public static void main(String[] args){
List<Node> list = new ArrayList<>();
list.add(new Node("A", "B"));
list.add(new Node("A", "C"));
list.add(new Node("B", "D"));
list.add(new Node("D", "F"));
list.add(new Node("D", "C"));
list.add(new Node("C", "B"));
list.add(new Node("C", "E"));
list.add(new Node("E", "F"));
findAllPath(list,"A","F");
}
}