Zepruv › Coding problems

Shortest Path Visiting All Nodes

Hard · Dynamic Programming, Bit Manipulation, Breadth-First Search, Graph, Bitmask

You have an undirected, connected graph of n nodes labeled from 0 to n - 1. You are given an array graph where graph[i] is a list of all the nodes connected with node i by an edge.
Return the length of the shortest path that visits every node. You may start and stop at any node, you may revisit nodes multiple times, and you may reuse edges.

Example 1

Input: graph = [[1,2,3],[0],[0],[0]]
Output: 4

One possible path is [1,0,2,0,3]

Example 2

Input: graph = [[1],[0,2,4],[1,3,4],[2],[1,2]]
Output: 4

One possible path is [0,1,4,2,3]

Constraints

Starter code (python)

class Solution(object):
    def shortestPathLength(self, graph):
        """
        :type graph: List[List[int]]
        :rtype: int
        """
        

Related problems

Previous: Longest Mountain in Array · Next: Loud and Rich · All problems

Zepruv is a technical interview practice platform. Read any problem for free; sign in to run your code, submit and keep your progress.