Fundamentals/Minimum Cost to Visit Every Node
← PrevNext →
Given a directed weighted graph as an n x n matrix where graph[i][j] is the edge weight from node i to j (0 means no edge), find the minimum total cost to start at node 0 and visit every node exactly once. You do not need to return to the start. Return -1 if it is impossible.
Input
graph: n x n adjacency matrix of non-negative integers
Output
The minimum total cost, or -1 if no valid path visits every node.
Examples
Example 1
Inputgraph = [[0,1,2],[1,0,3],[2,3,0]]
Output4
Example 2
Inputgraph = [[0,0],[1,0]]
Output-1
Constraints
1 <= n <= 16.
graph[i][i] == 0.