
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)
Editorial
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. |
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