Route Between Two Nodes in Graph

    xiaoxiao2021-12-14  17

    Given a directed graph, design an algorithm to find out whether there is a route between two nodes.

    Have you met this question in a real interview?  Yes Example

    Given graph:

    A----->B----->C \ | \ | \ | \ v ->D----->E

    for s = B and t = E, return true

    for s = D and t = C, return false

    这一到也比较简单,就是考察的递归怎么写,感觉连dfs都不是

    代码:

    public boolean hasRoute(ArrayList<DirectedGraphNode> graph, DirectedGraphNode s, DirectedGraphNode t) { // write your code here if(graph == null || s == null || t == null) return false; if(s == t) return true; ArrayList<DirectedGraphNode> neighbors = s.neighbors; for(DirectedGraphNode neighbor: neighbors){ if(hasRoute(graph, neighbor, t)){ return true; } } return false; }

    转载请注明原文地址: https://ju.6miu.com/read-963204.html

    最新回复(0)