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 all nodes in an undirected, connected graph. You are given an undirected, connected graph of n nodes labeled from 0 to n-1. The graph is represented by an adjacency matrix `graph` where `graph[i][j] = 1` indicates there is an edge between nodes i and j, and `graph[i][j] = 0` otherwise. Return the length of the shortest path that visits every node. You can start at any node and revisit nodes multiple times if needed.

Example 1
  • Input: graph = [[0,1,1,0],[1,0,1,0],[1,1,0,1],[0,0,1,0]]
  • Output: 4
  • Explanation:
    • One possible path is [0,1,2,3], which has length 3 edges.
    • However, to visit all nodes, we need to take [0,1,2,3,0] or similar, which has 4 edges.
Example 2
  • Input: graph = [[0,1,0,0],[1,0,1,0],[0,1,0,1],[0,0,1,0]]
  • Output: 4
  • Explanation:
    • The graph forms a line, and we need to traverse from one end to the other end, which requires 3 edges.
    • The shortest path is [0,1,2,3], which has length 3 edges.
Constraints
  • 1 ≤ n ≤ 12
  • graph[i][j] is 0 or 1
  • graph[i][i] == 0
  • graph is undirected (graph[i][j] == graph[j][i])
  • graph is connected
  • Time Complexity: O(n^2 * 2^n)
  • Space Complexity: O(n * 2^n)
GraphAlgorithmsGoldman SachsShopify
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 a breadth-first search (BFS) with a state representation including current node and visited nodes
  • Represent visited nodes using a bitmask
  • Use a queue to keep track of states to explore
  • Keep track of the visited states to avoid cycles
  • The first state to visit all nodes will give the shortest path

Steps to solve by this approach:

 Step 1: Define a state as (node, mask, distance) where node is the current node, mask is a bitmask of visited nodes, and distance is the path length so far.
 Step 2: Create a queue for BFS and initialize it with all possible starting nodes.
 Step 3: Create a visited array to keep track of states we have already explored.
 Step 4: For each state in the queue, check if all nodes have been visited (mask == targetMask).
 Step 5: If not, explore all neighboring nodes and add new valid states to the queue.
 Step 6: Keep track of the minimum distance required to visit all nodes.
 Step 7: Return the minimum distance once a state with all nodes visited is found.

Submitted Code :