Tutorialspoint
Problem
Solution
Submissions

Shortest Path Visiting All Nodes

Certification: Advanced Level Accuracy: 0% Submissions: 0 Points: 15

Write a C program to find the shortest path that visits every node in an undirected, connected graph exactly once and returns to any node. The path can start and end at any node. Return the length of the shortest such path. This is similar to the Traveling Salesman Problem but you can end at any node.

Example 1
  • Input: graph = [[1,2,3],[0],[0],[0]]
  • Output: 4
  • Explanation:
    • The graph has 4 nodes: 0 connected to [1,2,3], and nodes 1,2,3 each connected only to 0.
    • One optimal path: 0 → 1 → 0 → 2 → 0 → 3 (length 5).
    • Another optimal path: 1 → 0 → 2 → 0 → 3 (length 4).
    • The shortest path length is 4.
Example 2
  • Input: graph = [[1],[0,2,4],[1,3,4],[2],[1,2]]
  • Output: 4
  • Explanation:
    • The graph has 5 nodes with various connections.
    • One optimal path visits all nodes in 4 steps.
    • We can start from any node and visit all others.
    • The minimum path length is 4.
Constraints
  • 1 ≤ graph.length ≤ 12
  • 0 ≤ graph[i].length < graph.length
  • graph[i] does not contain i
  • graph[i] contains distinct values
  • Time Complexity: O(2^n * n^2)
  • Space Complexity: O(2^n * n)
QueueAlgorithmsEYPhillips
Editorial

Login to view the detailed solution and explanation for this problem.

My Submissions
All Solutions
Lang Status Date Code
You do not have any submissions for this problem.
User Lang Status Date Code
No submissions found.

Please Login to continue
Solve Problems

 
 
 
Output Window

Don't have an account? Register

Solution Hints

  • Use BFS with state (current_node, visited_mask) to explore all possibilities
  • Use bitmask to represent which nodes have been visited
  • The target state is when all nodes are visited (mask = (1<
  • Start BFS from all nodes simultaneously to find minimum path
  • Use a queue to store (node, mask, distance) tuples

Steps to solve by this approach:

Step 1: Use BFS with state representation (current_node, visited_bitmask)

Step 2: Initialize queue with all nodes as starting points, each with their bit set
Step 3: Use 2D visited array to track (node, mask) combinations
Step 4: For each state, explore all neighboring nodes
Step 5: Update bitmask by setting the bit for newly visited neighbor
Step 6: Continue BFS until all nodes are visited (mask equals (1Step 7: Return the distance when target state is reached

Submitted Code :