BackmediumUncategorized uncategorized medium

Shortest Node-Covering Path Solution

Problem Statement

You are given an undirected connected graph with N nodes, labeled from 0 to N - 1. The graph is represented as an adjacency list `graph` where `graph[i]` is a list of all nodes adjacent to node `i`. You are also given two integers `start` and `target`. Find the minimum length (measured by the number of edge traversals) of a path that starts at node `start`, ends at node `target`, and visits every node in the graph at least once. You may reuse edges and revisit nodes multiple times. If no such path exists, return -1. Note: A path with k nodes has k - 1 edge traversals.

Example 1
Input
graph = [[1, 2], [0, 2], [0, 1]] start = 0 target = 2
Output
undefined

Explanation: The path 0 -> 1 -> 2 visits all nodes {0, 1, 2}, starts at 0, and ends at 2 using 2 edge traversals.

Constraints

  • 1 <= graph.length <= 15
  • 0 <= graph[i].length < graph.length
  • graph[i] does not contain duplicate elements.
  • 0 <= start, target < graph.length
  • The input graph is connected.
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