Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- def findAllCycles(startState):
- stack = []
- for e in startState.outgoingEdges:
- newPath = [e]
- stack.append(newPath)
- while len(stack) > 0:
- path = stack[-1] # get last element that has been "pushed" onto the stack
- stack = stack[:-1] # remove the last element from the stack
- lastState = path[-1].targetState # path[-1] is the last edge of the path, thus lastState will be the state path ends up in
- cycleFound = False
- for i in range(len(path)): # iterate of all edges in the path
- 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
- print(path[i:]) # path[i:] is the subset of path that starts at index i and includes everything that follows after index i
- cycleFound = True
- if not cycleFound:
- # if no cycle was found, for each outgoing edge of lastState: extend copy of path and push onto stack
- # if a cycle was found, don't do anything otherwise this algorithm will never terminate if there are any cycles in the graph
- for e in lastState.outgoingEdges:
- newPath = [] # new empty path
- newPath.extend(path) # copy reference to edges
- newPath.append(e) # extend path by edge "e"
- stack.append(newPath) # add newly found path to stack
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement