Problem · Graph
Shortest Path Visiting All Nodes
Learn this problemProblem statement
You are given a connected, undirected graph with n nodes labeled from 0 to n - 1. The adjacency list graph[i] contains every node joined to node i by an edge.
Return the minimum number of edges in a walk that visits every node at least once. You may start and finish at any node, revisit nodes, and traverse an edge more than once.
Function
shortestPathLength(graph: int[][]) → intExamples
Example 1
graph = [[1,2,3],[0],[0],[0]]return = 4One shortest walk is 1 - 0 - 2 - 0 - 3, which uses four edges.
Example 2
graph = [[1],[0,2,4],[1,3,4],[2],[1,2]]return = 4A four-edge walk such as 0 - 1 - 4 - 2 - 3 visits all five nodes.
Constraints
1 <= n <= 12graph.length == n0 <= graph[i].length < ngraph[i]does not containior duplicate neighbors.- If
jappears ingraph[i], theniappears ingraph[j]. - The graph is connected.