File tree Expand file tree Collapse file tree 1 file changed +39
-1
lines changed
Expand file tree Collapse file tree 1 file changed +39
-1
lines changed Original file line number Diff line number Diff line change @@ -435,6 +435,9 @@ def bfs(self, s=-2) -> list[int]:
435435 Performs breadth-first search starting from node s.
436436 If s is not given, starts from the first node in the graph
437437
438+ Returns:
439+ list of nodes found after performing breadth-first search
440+
438441 >>> g = Graph()
439442 >>> g.add_pair(1,2)
440443 >>> g.add_pair(1,3)
@@ -527,7 +530,42 @@ def cycle_nodes(self):
527530 if len (stack ) == 0 :
528531 return list (anticipating_nodes )
529532
530- def has_cycle (self ):
533+ def has_cycle (self ) -> bool :
534+ """
535+ Detects whether the undirected graph contains a cycle.
536+
537+ Note:
538+ - This function assumes the graph is connected and only traverses from the first node found in the graph.
539+ - It does not detect cycles that exist in disconnected components.
540+ - It also does not detect self-loops (e.g., an edge from a node to itself like 1-1).
541+
542+ Returns:
543+ bool: True if a cycle is detected in the connected component starting from the first node; False otherwise.
544+
545+ >>> g = Graph()
546+ >>> g.add_pair(1, 2)
547+ >>> g.add_pair(2, 3)
548+ >>> g.has_cycle()
549+ False
550+ >>> g2 = Graph()
551+ >>> g2.add_pair(1, 2)
552+ >>> g2.add_pair(2, 3)
553+ >>> g2.add_pair(3, 1) # creates a cycle
554+ >>> g2.has_cycle()
555+ True
556+ >>> g3 = Graph()
557+ >>> g3.add_pair(1, 1) # self-loop
558+ >>> g3.has_cycle() # Self-loops are not detected by this method
559+ False
560+ >>> g4 = Graph()
561+ >>> g4.add_pair(1, 2)
562+ >>> g4.add_pair(3, 4)
563+ >>> g4.add_pair(4, 5)
564+ >>> g4.add_pair(5, 3) # cycle in disconnected component
565+ >>> g4.has_cycle() # Only checks the component reachable from the first node (1)
566+ False
567+ """
568+
531569 stack = []
532570 visited = []
533571 s = next (iter (self .graph ))
You can’t perform that action at this time.
0 commit comments