判斷有向圖中兩點之間是否存在路徑


對於一個有向圖,請實現一個算法,找出兩點之間是否存在一條路徑。給定圖中的兩個結點的指針UndirectedGraphNode*a,UndirectedGraphNode* b(請不要在意數據類型,圖是有向圖),請返回一個bool,代表兩點之間是否存在一條路徑(a到b或b到a)。

import java.util.*;

/*
public class UndirectedGraphNode {
    int label = 0;
    UndirectedGraphNode left = null;
    UndirectedGraphNode right = null;
    ArrayList<UndirectedGraphNode> neighbors = new ArrayList<UndirectedGraphNode>();

    public UndirectedGraphNode(int label) {
        this.label = label;
    }
}*/
public class Path {
    
    ArrayList<UndirectedGraphNode> nodeList = new ArrayList<UndirectedGraphNode>();
    boolean hasLine = false;
    
    public boolean checkPath(UndirectedGraphNode a, UndirectedGraphNode b) {
        return hasPath(a, b) || hasPath(b, a);
    }
    
    public boolean hasPath(UndirectedGraphNode a, UndirectedGraphNode b){
        if(a == b || hasLine){
            hasLine = true;
            return true;
        }else{
            if(!nodeList.contains(a)){
                nodeList.add(a);
            }else{
                return false;
            }
        }
        
        for(int i = 0; i < a.neighbors.size(); i++){
            hasPath(a.neighbors.get(i), b);
        }
        
        return hasLine;
    }
}
View Code

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM