MCPcopy Create free account
hub / github.com/TheAlgorithms/Python / has_cycle

Method has_cycle

graphs/directed_and_undirected_weighted_graph.py:424–474  ·  view source on GitHub ↗
(self)

Source from the content-addressed store, hash-verified

422 return list(anticipating_nodes)
423
424 def has_cycle(self):
425 stack = []
426 visited = []
427 s = next(iter(self.graph))
428 stack.append(s)
429 visited.append(s)
430 parent = -2
431 indirect_parents = []
432 ss = s
433 on_the_way_back = False
434 anticipating_nodes = set()
435
436 while True:
437 # check if there is any non isolated nodes
438 if len(self.graph[s]) != 0:
439 ss = s
440 for node in self.graph[s]:
441 if (
442 visited.count(node[1]) > 0
443 and node[1] != parent
444 and indirect_parents.count(node[1]) > 0
445 and not on_the_way_back
446 ):
447 len_stack_minus_one = len(stack) - 1
448 while len_stack_minus_one >= 0:
449 if stack[len_stack_minus_one] == node[1]:
450 anticipating_nodes.add(node[1])
451 break
452 else:
453 return True
454 if visited.count(node[1]) < 1:
455 stack.append(node[1])
456 visited.append(node[1])
457 ss = node[1]
458 break
459
460 # check if all the children are visited
461 if s == ss:
462 stack.pop()
463 on_the_way_back = True
464 if len(stack) != 0:
465 s = stack[len(stack) - 1]
466 else:
467 on_the_way_back = False
468 indirect_parents.append(parent)
469 parent = s
470 s = ss
471
472 # check if se have reached the starting point
473 if len(stack) == 0:
474 return False
475
476 def all_nodes(self):
477 return list(self.graph)

Callers

nothing calls this directly

Calls 4

countMethod · 0.80
appendMethod · 0.45
addMethod · 0.45
popMethod · 0.45

Tested by

no test coverage detected