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

来源:互联网 发布:二手索尼z3淘宝 编辑:程序博客网 时间:2024/06/05 15:49

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 discovered3      for all edges from v to w in G.adjacentEdges(v) do4          if vertex w is not labeled as discovered then5              recursively call DFS(G,w)

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

1  procedure DFS-iterative(G,v):2      let S be a stack3      S.push(v)4      while S is not empty5          v = S.pop()6          if v is not labeled as discovered:7              label v as discovered8              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});      }    }  }}
阅读全文
0 0
原创粉丝点击