【问题标题】:Using depth first search to find the number of unique routes to a node [duplicate]使用深度优先搜索来查找到节点的唯一路由的数量[重复]
【发布时间】:2016-05-30 18:11:16
【问题描述】:

我有一个顶点为 ABCDE 的有向图。使用深度优先搜索,如果我希望能够从 A-C 找到唯一路线的数量(例如),我将如何去做?这是我目前的 DFS。

private final Map<Character, Node> mNodes;
private final List<Edge> mEdges;
private List<Node> mVisited = new ArrayList<>();
int weight;
int numberOfPaths;

public DepthFirstSearch(Graph graph){
    mNodes = graph.getNodes();
    mEdges = new ArrayList<>(graph.getEdges());
    for(Node node : mNodes.values()){
        node.setVisited(false);
    }
}

public void depthFirstSearch(Node source){

    source.setVisited(true);
    List<Edge> neighbours = source.getNeighbouringEdges(mEdges);
    for(Edge edge : neighbours){
        System.out.println(edge.getFrom().getName()+"-"+edge.getTo().getName());
        if(!edge.getTo().isVisited()){

            mVisited.add(edge.getTo());
            weight += edge.getWeight();
            depthFirstSearch(edge.getTo());

        }
    }

【问题讨论】:

  • 如果图形包含循环,则路径数可能是无限的。也许您的图表恰好是非循环的?
  • 图中没有循环 :)

标签: java algorithm depth-first-search


【解决方案1】:

假设图表是DAG(即图表中没有循环),您可以使用dynamic programming 并在线性时间内解决您的问题。

以下琐碎的声明描述了图中从uv 的路径数:

如果u=v,则从uv 的路径数为1。否则,从uv 的路径数是从w 的路径总数到v 使得(u,w) 是图中的一条边。

声明暗示了一个简单的递归算法,由以下伪代码给出。请注意,下面的伪代码不使用动态编程,而是使用简单的递归。如果您需要在线性时间内解决问题,您应该使用memoization

def count_paths(u,v):
    if u == v: return 1
    count = 0
    for each edge (u,w):
        count += count_paths(w,v)
    return count

这是Java代码:

public int countPaths(Graph graph, Node u, Node v) {
    nodes = graph.getNodes();
    edges = new ArrayList<>(graph.getEdges());
    if (u.equals(v)) return 1;
    int count = 0;
    List<Edge> neighbours = u.getNeighbouringEdges(edges);
    for(Edge edge : neighbours){
        w = edge.getTo();
        count += countPaths(graph, w, v);
    }
    return count;
}

【讨论】:

  • 此方法似乎没有显示唯一路径。我两次得到相同的路径。
  • @spogebob92,你能提供一个算法过度计数的简单例子吗?
猜你喜欢
  • 2016-09-26
  • 2017-03-04
  • 1970-01-01
  • 1970-01-01
  • 2017-06-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多