Skip to content

Commit 29be7b6

Browse files
committed
Add doctest and type hints to Graph.has_cycle; note cycle detection limitations for disconnected graphs
1 parent a056d2e commit 29be7b6

File tree

1 file changed

+39
-1
lines changed

1 file changed

+39
-1
lines changed

graphs/directed_and_undirected_weighted_graph.py

Lines changed: 39 additions & 1 deletion
Original file line numberDiff line numberDiff 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))

0 commit comments

Comments
 (0)