Python:Depth-First-Search(DFS)输出订购后编号

时间:2018-02-12 05:25:49

标签: python algorithm graph depth-first-search

我想找出具有相同元组元素的元组节点(例如(1,1),(2,2)或(i,i))是特定图形中的源,即哪个节点具有最高的订单号。我想通过将DFS应用于它来找到源,并将具有最高序列号的数字作为我的源节点以供进一步使用。假设您有以下图表:

graph={
    (1,1): [(1,2),(2,2)],
    (1,2): [(1,3)],
    (1,3): [(1,2),(2,3)],
    (2,2): [(3,3)],
    (2,3): [],
    (3,3): [(2,2)],
}

现在我有了这个迭代的dfs函数(我必须迭代地执行它,因为我有一个庞大的堆栈)。我不知道如何扩展它以返回订单号最高的节点。

def dfs_iterative_starting(graph, n):
    # n is the number different numbers (e.g. (1,1), (2,2) or (i,i))
    # array in which I'll save the post-order numbers. The index indicates the node, e.g. index 1 -> (1,1)
    arr = [0]*(n+1)
    # starting node is (1,1)
    stack, path = [(1,1)], []
    # counter for the post-order number
    counter = 1
    while stack:
        vertex = stack.pop()
        if vertex in path:
            continue
        path.append(vertex)

        # counting post-order number????
        i, j = vertex
        if i == j:
            arr[i] = counter
        for neighbor in graph[vertex]:
            stack.append(neighbor)

            # counting post-order number????
            k, j = neighbor
            counter += 1
            if k == j:
                arr[k] = counter
    print(arr)
    return arr.index(max(arr))

对于上述示例,即使正确答案为1,它也会返回2。 如果我打印arr,我会得到以下列表[0,1,5,4]

1 个答案:

答案 0 :(得分:1)

在递归实现中,我们有一个后续操作,将我们首先探索的邻居添加到后序列表中。必须首先将其推送到堆栈。它可能有助于区分如何处理堆栈元素。这是一个例子:

JavaScript代码(抱歉,在智能手机上无法访问Python):



function f(graph){
  let stack = [['(1,1)', 'explore']];
  let path = new Set();
  let post_order = [];

  while (stack.length){
    let [vertex, action] = stack.pop();

    if (action == 'mark'){
      post_order.push(vertex);
      continue;
    }

    path.add(vertex);
    stack.push([vertex, 'mark']);

    for (let neighbour of graph[vertex]){
      if (!path.has(neighbour))
        stack.push([neighbour, 'explore']);
    }
  }
  
  console.log('Path: ' + JSON.stringify(Array.from(path)));
  
  return post_order;
}

var g = {
    '(1,1)': ['(1,2)','(2,2)'],
    '(1,2)': ['(1,3)'],
    '(1,3)': ['(1,2)','(2,3)'],
    '(2,2)': ['(3,3)'],
    '(2,3)': [],
    '(3,3)': ['(2,2)'],
}

/*
(1,1) -> (1,2) <-> (1,3) -> (2,3)
 \
 (2,2) <-> (3,3)
*/

console.log(JSON.stringify(f(g)));
&#13;
&#13;
&#13;