Graphs Cycle detection
453. Cycle in an Undirected Graph
You are given an undirected graph with n vertices, numbered from 0 to n - 1. Each pair [u, v] in
edges is an edge between vertices u and v, and it can be used in both directions.
Return true if the graph has a cycle, and false otherwise. A cycle is a way to leave a vertex along
one edge and come back to it along another, without using any edge twice.
The graph can be in several pieces, with no edges between them. A cycle in any piece counts.
Example 1
Input: n = 6
edges = [[0, 1],
[1, 2],
[2, 5],
[5, 1],
[3, 4]]
trueExplanation: We can leave vertex 1 along the edge to 2, go on to 5, and come back to 1 along the edge [5,1].
Vertices 3 and 4 form a piece of their own, which does not change the answer.
Example 2
Input: n = 5, edges = [[0, 2], [2, 4], [1, 3]]
falseExplanation: Vertices 0, 2 and 4 form a path, and 1 and 3 are joined by a single edge. In both pieces, the only way back to a vertex is along the edge we just used.
Example 3
Input: n = 1, edges = []
falseCheck your understanding
Work out the answer for this input before you write any code.
Constraints
1 ≤ n ≤ 1050 ≤ edges.length ≤ 2 × 105edges[i].length == 20 ≤ ui, vi < nui ≠ vi- No edge appears twice:
[u, v]and[v, u]are the same edge.
Clarifying questions
What you would ask an interviewer before writing any code.