【问题标题】:Writing a DFS with iterative deepening without recursion编写一个没有递归的迭代深化的 DFS
【发布时间】:2011-09-21 02:10:45
【问题描述】:

所以目前我有一个带有以下伪代码的 DFS

procedure DFS(Graph,source):
      create a stack S
      push source onto S
      mark source
      while S is not empty:
          pop an item from S into v
          for each edge e incident on v in Graph:
              let w be the other end of e
              if w is not marked:
                 mark w
                 push w onto S

如何更改此函数以接受限制搜索深度的第三个参数?

【问题讨论】:

  • 这不是完全正确的 DFS 算法。它首先访问顶点的所有后继,然后再深入。它应该先深入,然后回溯访问其他子节点。

标签: graph stack graph-theory depth-first-search iterative-deepening


【解决方案1】:

Node为图的每个节点建立一个结构,添加一个名为level的字段然后:

procedure DFS(Graph,source, depth):
  create a stack S
  source.level = 0
  push source onto S
  mark source
  while S is not empty:
      pop an item from S into v
      if v.level > depth
        continue

      for each edge e incident on v in Graph:
          let w be the other end of e
          if w is not marked:
             mark w
             w.level = v.level + 1
             push w onto S

【讨论】:

  • 将每个邻居都推入堆栈会产生 BFS,因为您最终会在孩子之前先查看邻居。
  • 没有。这里的重点是数据结构,如果使用队列则得到 BFS,使用堆栈则得到 DFS。
  • 我认为上述解决方案存在一些问题。您不能立即将 S 中的项目弹出到 V 中
  • @ThinkRecursively 我知道它看起来像 Python 或任何其他语言,但它是伪代码:pop an item from S into v 可以翻译成许多指令。
  • 你的伪代码不正确。您在同一迭代中标记了所有 w,因此它不能是 DFS;虽然@Matilda 的评论也不正确,但他/她指出您的答案可能不正确,然后一个有理智的人会检查一个人的答案。但是你说“不,这里的关键是数据结构”,
【解决方案2】:
  1. 找到对象时,该过程将返回success
  2. 找到对象后,S 将包含路径 [root, source) 中的节点。 (source 本身不包括在内。)

procedure DFS(Graph, source, depth):
    StackInit(S)
    if source is goal then
        return success
    markVisited(source)
    S.push(null, source)              // S is a close-list
    while S is not empty then do
        c, p := S.pop()
        r := next(c, p)               // return the next sibling of c
        if r is null then
            continue
        S.push(r, p)
        if r is marked visited then   // that already marked means it cannot be goal
            continue
        if r is goal then
            return success
        markVisited(r)
        if equal(depth(r), depth) then // here is what OP wants.
            continue
        S.push(null, r)

return fail

【讨论】:

    猜你喜欢
    • 2015-02-27
    • 2015-01-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-09-22
    • 1970-01-01
    • 2013-05-01
    • 1970-01-01
    相关资源
    最近更新 更多