logo
down
shadow

Transforming recursive DFS-based topological sort into a non-recursive algorithm (without losing cycle detection)


Transforming recursive DFS-based topological sort into a non-recursive algorithm (without losing cycle detection)

By : user2948635
Date : November 14 2020, 04:51 PM
To fix this issue Obviously, you'd use a stack but you wouldn't put all adjacent nodes anyway: that would yield a DFS with the wrong size complexity anyway (it would be quadratic in the number of nodes assuming non-parallel edges, otherwise potentially worse). Instead, you'd store the current node together with a state indicating the next node to be visited. You'd always work off the stack's top, i.e., something like this:
code :
std::stack<std::pair<node, iterator> stack;
stack.push(std::make_pair(root, root.begin()));
while (!stack.empty()) {
    std::pair<node, iterator>& top = stack.top();
    if (top.second == top.first.begin()) {
        mark(top.first);
        // do whatever needs to be done upon first visit
    }
    while (top.second != top.first.end() && is_marked(*top.second)) {
        ++top.second;
    }
    if (top.second != top.first.end()) {
        node next = *top.second;
        ++top.second;
        stack.push(std::make_pair(next, next.first());
    }
    else {
        stack.pop();
    }
}


Share : facebook icon twitter icon
Topological sort, recursive, using generators

Topological sort, recursive, using generators


By : Bridgier
Date : March 29 2020, 07:55 AM
hop of those help? Data: a dependency list, already verified to be acyclic. So here, 'a' depends on 'b','c' (c depends on d), etc... , Try this:
code :
#!/usr/bin/env python

def get_all(D, k):
    yield k
    for ii in D.get(k, []):
        for jj in get_all(D, ii):
            yield jj

A = { 'a' : dict(b=1, c=1),
    'c' : dict(d=1),
    'd' : dict(e=1,f=1,g=1),
    'h' : dict(j=1)
    }

for ii in get_all(A,'a'):
    print ii
steve@rei:~/code/tmp
$ python recur.py
a
c
d
e
g
f
b
Cycle detection with recursive subquery factoring

Cycle detection with recursive subquery factoring


By : user1564302
Date : March 29 2020, 07:55 AM
Any of those help From documentation on CONNECT_BY_ISCYCLE:
Is Topological sort different from DFS only in that processing of current element is done after recursive call

Is Topological sort different from DFS only in that processing of current element is done after recursive call


By : messi
Date : March 29 2020, 07:55 AM
it fixes the issue Not exactly. DFS is the generic form. You can use it to implement a pre and/or post order evaluation.
Topological sort requires a post evaluation DFS.
code :
void DFS(Vertex v) {
  if (v.hasVisited)
    return;
  v.hasVisited = true;
  doBeforeDepth(v)
  for (Vertex u : v.neighbours)
    DFS(u);
  doAfterDepth(v);
}

void DFS()
{
    for (Vertex v : vertices)
        DFS(v);
}
Tail recursive algorithm for generating all topological orderings in a graph

Tail recursive algorithm for generating all topological orderings in a graph


By : Praburaam Jayaraman
Date : March 29 2020, 07:55 AM
To fix the issue you can do Implementing this variation on topological sort without blowing up the stack and without computing all possibilities at once has been painful. I ended up with the following implementation:
code :
import scalax.collection.Graph
import scalax.collection.GraphPredef._
import scalax.collection.GraphEdge._
import scala.collection.Set

object test extends App {

  class TopSorter[T](val graph: Graph[T, DiEdge]) extends Iterator[List[T]] {

    final case class State[Node](indegrees: Map[Node, Int], topo: List[Node])

    sealed trait TopoRes
    final case class Res(order: List[graph.NodeT], sorter: Set[State[graph.NodeT]]) extends TopoRes
    final case object Nil extends TopoRes

    private[this] val indegs: Map[graph.NodeT, Int] = graph.nodes.map(node => (node, node.inDegree)).toMap
    private[this] var nextOrder = nextTopo(Set(State(indegs, List[graph.NodeT]())))

    override def hasNext: Boolean = nextOrder.isInstanceOf[Res]

    override def next(): List[T] = nextOrder match {
      case Res(order, sorter) => {
        nextOrder = nextTopo(sorter)
        order.map(_.value)
      }
      case Nil => throw new NoSuchElementException("next on empty iterator")
    }

    private def nextTopo(w: Set[State[graph.NodeT]]): TopoRes = {
      if (w.isEmpty) {
        Nil
      }
      else {
        w.head match {
          case State(indegrees, topo) => {
            val sources = indegrees.keySet.filter(indegrees.get(_).get == 0)
            if (sources.isEmpty) {
              Res(topo.reverse, w.tail) // The result is the order + state to compute the next order
            }
            else {
              sourcesLoop(sources, w.tail, topo, indegrees)
            }
          }
        }
      }
    }

    private def sourcesLoop(sources: Set[graph.NodeT], w: Set[State[graph.NodeT]], topo: List[graph.NodeT], indegrees: Map[graph.NodeT, Int]): TopoRes = {
      if (sources.isEmpty) {
        nextTopo(w)
      }
      else {
        val source = sources.head
        succLoop(source.diSuccessors, indegrees - source, sources, w, source, topo, indegrees)
      }
    }

    private def succLoop(succs: Set[graph.NodeT], indegrees: Map[graph.NodeT, Int], sources: Set[graph.NodeT], w: Set[State[graph.NodeT]], source: graph.NodeT, topo: List[graph.NodeT], oldIndegrees: Map[graph.NodeT, Int]): TopoRes = {
      if (succs.isEmpty) {
        sourcesLoop(sources.tail, w + State(indegrees, source :: topo), topo, oldIndegrees)
      }
      else {
        val succ = succs.head
        succLoop(succs.tail, indegrees.updated(succ, indegrees.get(succ).get - 1), sources, w, source, topo, oldIndegrees)
      }
    }
  }

  val graph: Graph[Int, DiEdge] = Graph(2 ~> 4, 2 ~> 7, 4 ~> 5)
  val it = new TopSorter(graph)

  while (it.hasNext)
    println(it.next())
}
MySQL recursive cycle detection procedure

MySQL recursive cycle detection procedure


By : John Z
Date : March 29 2020, 07:55 AM
around this issue Try to reset this mysql variable: max_sp_recursion_depth, thread_stack
Related Posts Related Posts :
  • Stuck when testing custom list class in c++
  • Using each member of class within one function to calculate average
  • check whether if two squares are intersecting with each other
  • Glm Quaternion lookat function
  • Is there guarantee heap allocated block address will not change(implicitly)?
  • Cosine Calculation without cmath library
  • Manually deleting a pointer returned by function
  • Avoid output interleaving
  • C++ error : Expected an identifier
  • Segmentation fault when I call operator new in linux mint
  • Recursively Solving A Sudoku Puzzle Using Backtracking Theoretically
  • lambda closure type and default argument in function template
  • How to ensure the function return consistent floating point values in C/C++?
  • What does throw do when not in used with try and catch?
  • The Unpredictablilty of the Order of Evaluation of Subexpressions
  • cannot convert const wchar_t to 'const_char' for argument 2 in MessageBOX etc etc
  • Size of a empty Class & Derived Virtual Class
  • unformatted i/o to and from memory
  • Storing an std::thread object as a class member
  • Remove duplicate string in an array
  • How to use copy_if() polymorphically?
  • How to organize a class's member functions?
  • How to wrap std::chrono in a c++ iterator type
  • Check if a socket is connected in mac os x
  • Grabbing the mouse cursor in GLFW
  • Calling Windows shell menu (same as right-click in Explorer) for multiple files programmatically
  • Pop up dialog to save file in seperate thread
  • Why would you use the keyword const if you already know variable should be constant?
  • Detecting Small Sound Effects In C++
  • How to avoid the copy when I return
  • Getting error code C2228: left of '._Ptr' must have class/struct/union
  • In win32 C++ programming how can I duplicate a window style?
  • Should the order of import statements matter when importing a .so?
  • Design decision regarding std::array fill
  • Access array of C++ structs from Fortran?
  • Determining when functions allocate memory in C++
  • C++ using std::set remove duplicate item for a struct fail.
  • Code to find out the number of triplets which lead to a sum less than or equal to threshold is giving a wrong output
  • Converting glm::lookat matrix to quaternion and back
  • Searching multi-dimensional vectors
  • Send and receive via SOCKS5 c++
  • GDI+: unhandled exception when drawing bitmap
  • Editing other processes memory
  • Object deleted when its member function is being executed?
  • Infinite Loop while inputting the different data type values in STACK
  • const members and operator=
  • Threaded Video Player sync
  • Does infinite of floating point number satisfy these equation?
  • map sorting in c++ by the frequencies
  • The Preprocessor program linked in g++ similar to the cpp program in gcc
  • How is the union used in this OpenCV library?
  • C++ memory leak in recursion
  • C++ Error: C4430 and C2143 Error at an impossible place
  • How can I track object lifetime in C++11 lambda?
  • #include statement mapping in Biicode (biicode.conf)
  • std::equal gives "Term doesnt evaluate to a function taking 2 arguments"
  • C++ template argument as reference lvalue
  • Legal to forward declare C standard library entities but not C++ standard library entities?
  • Conversion of wchar_t* to string
  • VirtualTreeView - Embarcadero C++ Builder XE7 - 64 bits
  • shadow
    Privacy Policy - Terms - Contact Us © ourworld-yourmove.org