使用迭代加深编写DFS而不递归

时间:2011-09-21 02:10:46

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

所以目前我有一个带有以下伪代码的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

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

2 个答案:

答案 0 :(得分:1)

节点为图表的每个节点构建一个结构,添加一个名为 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

答案 1 :(得分:0)

  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