mol
mol

Reputation: 63

Detect cycle in a directed graph using iterative stack approach

This is what I tried:

VISITED = 1
UNVISITED = -1
VISITING = 0


def dfs(g, start, num):
    
    state = {}
    for i in range(num):
        state[i] = UNVISITED
    
    
    stack = [start]
    while(stack != []):
        node = stack.pop()
        
        if(state[node] == VISITED):
            continue

        state[node] = VISITING
        
        if(node in g):
            for i in g[node]:
                stack.append(i)
                if(state[i] == VISITED):
                    return True
                
        state[node] = VISITED
 
def detect_cycle(n, edges):
        
    g = {}
    # adjacency list
    for (x, y) in edges:
        g[x] = g.get(x, []) + [y]

    for i in range(n):
        if(i in g):
            if(dfs(g, i, n) == True):
                return True   
    return False   
            
print(detect_cycle(5, [[1,4],[2,4],[3,1],[3,2]])) # outputs True (should be false)

Image of the graph:

The graph

The above example where edges = [[1,4],[2,4],[3,1],[3,2]] doesn't contain a cycle but it returns True. So my algorithm does not work for that case.

I'm trying to use the coloring graph detect cycle algorithm but I am unsure how to do that without recursion.

The algorithm I'm trying to follow but iteratively: Detecting a cycle in a directed graph using DFS?

Upvotes: 1

Views: 608

Answers (1)

mol
mol

Reputation: 63

A cycle is detected if a visiting node (gray) encounters an edge with another visiting node. The issue I had with initial code was there was no way to set a node VISITED (black) in a backtracking way. The new code now has ENTER = 0 and EXIT = 1. Enter = 0 means its the first time I visited that node and I set it to gray (visiting) the second time I visit the node exit will be 1 so i can then set it to black (fully visited).

WHITE = 0
GRAY = 1
BLACK = 2

ENTER = 0
EXIT = 1


def dfs(graph, start, n):
    
    state = {}
    for i in range(n):
        state[i] = WHITE

    stack = [(start, ENTER)]
    while(stack != []):
        node, pos = stack.pop()
        
        if(pos == EXIT):
            state[node] = BLACK
            continue
        
        state[node] = GRAY
        stack.append((node, EXIT))
        
        if(node in graph):
            for v in graph[node]:
                if state[v] == GRAY:
                    return True
                elif(state[v] == WHITE):
                    stack.append((v, ENTER))
    return False
  
def detect_cycle(n, edges):
        
    g = {}
    for (x, y) in edges:
        g[x] = g.get(x, []) + [y]

    for i in range(n):
        
        if(i in g):
            if(dfs(g, i, n) == True):
                return True
            
    return False

Upvotes: 1

Related Questions