BackhardGraphs

Closed Path Validator Solution

Problem Statement

Given a set of interconnected nodes, determine whether a cycle exists within the network and identify the length of the shortest cycle.

Example 1
Input
[[1,2],[2,3],[3,4],[4,1]]
Output
-1

Explanation: A cycle is present: 1 -> 2 -> 3 -> 4 -> 1, with a length of 4.

Example 2
Input
[[1,5],[5,6],[6,7],[7,8],[8,1]]
Output
-1

Explanation: The shortest cycle in this graph is: 1 -> 5 -> 6 -> 7 -> 8 -> 1, with a length of 5.

Example 3
Input
[[1,9],[9,10]]
Output
-1

Explanation: No cycle exists in the given graph, as there are only two nodes connected without forming a loop.

Constraints

  • The number of nodes in the graph will not exceed 1000
  • Each edge is represented as an array of two integers, denoting a connection between the nodes
  • The graph is undirected and may contain self-loops or multiple edges between nodes
Live Compiler
Loading...
Test Cases & Output
🔒 Sign up to run your code

🚀 Practice this problem

Run code, get AI hints & track streak

Sign Up Free