Given an undirected graph with n nodes labeled from 0 to n - 1 and a list of edges where edges[i] = [u, v] represents an undirected edge between nodes u and v, determine whether the graph contains a cycle.
Return True if the graph contains at least one cycle, otherwise return False. The graph may be disconnected, so make sure to check all connected components.
Function Signature
def has_cycle(n: int, edges: list[list[int]]) -> bool:
Rules
-
Edges are undirected:
[u, v]
and
[v, u]
describe the same edge.
-
A cycle is a path that starts and ends at the same node, uses at least one edge, and never reuses an edge. Walking an edge forward and straight back does not count.
-
Nodes that appear in no edge are valid isolated nodes.
-
The input has no self-loops and no repeated edges, so any cycle passes through at least three distinct nodes.
Constraints
-
1 <= n <= 10^5
-
0 <= len(edges) <= 10^5
-
len(edges[i]) == 2
-
0 <= edges[i][0], edges[i][1] < n
-
There are no self-loops or multiple edges between the same pair of nodes.
Examples
Input: n = 5, edges = [[0, 1], [1, 2], [2, 3], [3, 4], [4, 1]]
Output: True
Graph:
0 - 1 - 2
| |
4 - 3
The edges 1-2, 2-3, 3-4 and 4-1 form the cycle 1 -> 2 -> 3 -> 4 -> 1.
Input: n = 4, edges = [[0, 1], [1, 2], [2, 3]]
Output: False
Graph:
0 - 1 - 2 - 3
This is a simple path (a tree), so no cycle exists.
Input: n = 6, edges = [[0, 1], [2, 3], [3, 4], [4, 2]]
Output: True
The graph has three components: {0, 1}, {2, 3, 4} and the isolated node 5. The component {2, 3, 4} is a triangle, so the graph has a cycle even though the component containing node 0 does not.