• 判断有向图中两点之间是否存在路径


    对于一个有向图,请实现一个算法,找出两点之间是否存在一条路径。给定图中的两个结点的指针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
  • 相关阅读:
    VS密钥
    继承中delelte对象子类析构函数不被执行
    [LeetCode] Merge k Sorted Lists
    [LeetCode] Spiral Matrix II
    [LeetCode] Multiply Strings
    [LeetCode] Valid Number
    [LeetCode] Search Insert Position
    [LeetCode] Spiral Matrix
    [LeetCode] Valid Parentheses
    [LeetCode] Rotate List
  • 原文地址:https://www.cnblogs.com/liujinyao/p/4710468.html
Copyright © 2020-2023  润新知