Advertisement
Guest User

Untitled

a guest
Jul 17th, 2018
74
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.24 KB | None | 0 0
  1. def findAllCycles(startState):
  2.     stack = []
  3.     for e in startState.outgoingEdges:
  4.         newPath = [e]
  5.         stack.append(newPath)
  6.     while len(stack) > 0:
  7.         path = stack[-1] # get last element that has been "pushed" onto the stack
  8.         stack = stack[:-1] # remove the last element from the stack
  9.         lastState = path[-1].targetState # path[-1] is the last edge of the path, thus lastState will be the state path ends up in
  10.         cycleFound = False
  11.         for i in range(len(path)): # iterate of all edges in the path
  12.             if path[i].sourceState == lastState: # there is a state along the path that is equal to the last state, i.e., there is a cycle
  13.                 print(path[i:]) # path[i:] is the subset of path that starts at index i and includes everything that follows after index i
  14.                 cycleFound = True
  15.         if not cycleFound:
  16.             # if no cycle was found, for each outgoing edge of lastState: extend copy of path and push onto stack
  17.             # if a cycle was found, don't do anything otherwise this algorithm will never terminate if there are any cycles in the graph
  18.             for e in lastState.outgoingEdges:
  19.                 newPath = [] # new empty path
  20.                 newPath.extend(path) # copy reference to edges
  21.                 newPath.append(e) # extend path by edge "e"
  22.                 stack.append(newPath) # add newly found path to stack
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement