Writing a DFS with iterative deepening without rec

2019-06-12 22:06发布

So currently i have a DFS with the following pseudocode

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

How do I alter this function to accept a third argument that limits the depth of the search?

1条回答
Evening l夕情丶
2楼-- · 2019-06-12 22:19

Let Node a structure for each node of the graph, add a field called level and then:

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
查看更多
登录 后发表回答