TensorFlow中的深度优先搜索(Depth-first search, DFS)

TensorFlow中的深度优先搜索(Depth-first search, DFS)

flyfish

《数据结构、算法与应用:C++语言描述》

深度优先搜索(Depth-first search, DFS)从顶点v 出发,DFS按如下 过程进行:首先将v
标记为已到达顶点,然后选择一个与v 邻接的尚未到达的顶点u,如果这样 的u 不存在,搜索中止。假设这样的u 存在,那么从u
又开始一个新的DFS。当从u 开始的搜索 结束时,再选择另外一个与v 邻接的尚未到达的顶点,如果这样的顶点不存在,那么搜索终止。
而如果存在这样的顶点,又从这个顶点开始DFS,如此循环下去。

关于伪代码

Input: A graph G and a vertex v of G
Output: All vertices reachable from v labeled as discovered

递归实现的伪代码

1  procedure DFS(G,v):
2      label v as discovered
3      for all edges from v to w in G.adjacentEdges(v) do
4          if vertex w is not labeled as discovered then
5              recursively call DFS(G,w)

非递归实现的伪代码(stack来存储未被访问的节点,以便回溯时能够找到)

1  procedure DFS-iterative(G,v):
2      let S be a stack
3      S.push(v)
4      while S is not empty
5          v = S.pop()
6          if v is not labeled as discovered:
7              label v as discovered
8              for all edges from v to w in G.adjacentEdges(v) do 
9                  S.push(w)

关于深度优先搜索 源码位置tensorflow\core\graph algorithm.cc文件中

TensorFlow采用的是 非递归实现的算法

// Perform a depth-first-search on g starting at the source node.

// If enter is not empty, calls enter(n) before visiting any children of n.

// If leave is not empty, calls leave(n) after visiting all children of n.

void DFS(const Graph& g, const std::function<void(Node*)>& enter,
         const std::function<void(Node*)>& leave) {
  // Stack of work to do.
  struct Work {
    Node* node;
    bool leave;  // Are we entering or leaving n?
  };
  std::vector<Work> stack;
  stack.push_back(Work{g.source_node(), false});

  std::vector<bool> visited(g.num_node_ids(), false);
  while (!stack.empty()) {
    Work w = stack.back();
    stack.pop_back();

    Node* n = w.node;
    if (w.leave) {
      leave(n);
      continue;
    }

    if (visited[n->id()]) continue;
    visited[n->id()] = true;
    if (enter) enter(n);

    // Arrange to call leave(n) when all done with descendants.
    if (leave) stack.push_back(Work{n, true});

    // Arrange to work on descendants.
    for (Node* out : n->out_nodes()) {
      if (!visited[out->id()]) {
        // Note; we must not mark as visited until we actually process it.
        stack.push_back(Work{out, false});
      }
    }
  }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

西笑生

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值