
Problem
Solution
Submissions
Shortest Path Visiting All Nodes
Certification: Advanced Level
Accuracy: 100%
Submissions: 1
Points: 15
Write a Java program to find the shortest path length to visit all nodes in an undirected connected graph. You are allowed to start at any node, visit nodes multiple times, and revisit edges if necessary. The length of a path is the number of edges visited.
Example 1
- Input: graph = [[1,2,3],[0],[0],[0]]
- Output: 4
- Explanation:
Step 1: The graph has 4 nodes labeled 0, 1, 2, and 3, with the following connections: - Node 0 is connected to nodes 1, 2, and 3 - Nodes 1, 2, and 3 are each only connected to node 0
Step 2: One possible shortest path is: Start at node 0 → go to node 1 → back to node 0 → go to node 2 → back to node 0 → go to node 3.
Step 3: This path uses 5 edges (0→1, 1→0, 0→2, 2→0, 0→3), but since we count unique edges, the length is 4. Step 4: Therefore, the shortest path length is 4.
Example 2
- Input: graph = [[1],[0,2,4],[1,3,4],[2],[1,2]]
- Output: 4
- Explanation:
Step 1: The graph has 5 nodes with connections as shown in the input.
Step 2: One possible shortest path is: Start at node 0 → go to node 1 → go to node 2 → go to node 3 → back to node 2 → go to node 4.
Step 3: This path uses 5 edges (0→1, 1→2, 2→3, 3→2, 2→4). Step 4: Since we've visited all nodes and used 5 edges, the shortest path length is 4.
Constraints
- 1 <= graph.length <= 12
- 0 <= graph[i].length < graph.length
- graph[i] does not contain i
- graph[i] is sorted in ascending order
- The graph is connected
- Time Complexity: O(n * 2^n), where n is the number of nodes
- 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) approach combined with a bit mask to track visited nodes
- The state of our search should include (current node, visited nodes mask)
- Use a bit mask to represent the set of visited nodes (each bit position i represents whether node i has been visited)
- Start BFS from every node to handle any possible starting position
- Use a set or another data structure to keep track of visited states to prevent cycles
- The first time all nodes are visited (mask has all bits set to 1), we have found the shortest path
- Consider using a queue to implement the BFS