![]() |
VOOZH | about |
Given a 2d matrix cost[][] of size n where cost[i][j] denotes the cost of moving from city i to city j. The task is to complete a tour from city 0 (0-based index) to all other cities such that we visit each city exactly once and then at the end come back to city 0 at minimum cost.
Note the difference between Hamiltonian Cycle and TSP. The Hamiltonian cycle problem is to find if there exists a tour that visits every city exactly once. Here we know that Hamiltonian Tour exists (because the graph is complete) and in fact, many such tours exist, the problem is to find a minimum weight Hamiltonian Cycle.
Examples:
Input: cost[][] = [[0, 111], [112, 0]]
Output: 223
Explanation: We can visit 0->1->0 and cost = 111 + 112 = 223.Input: cost[][] = [[0, 1000, 5000], [5000, 0, 1000], [1000, 5000, 0]]
Output: 3000
Explanation: We can visit 0->1->2->0 and cost = 1000 + 1000 + 1000 = 3000.
Approach:
To solve the problem, we start by considering city 1(the 0th node) as both the starting and ending point, given the cyclic nature of the route, which makes any node a valid starting point. The solution involves a Depth-First Search (DFS) approach, where we recursively explore all possible paths from the starting node to its adjacent nodes. During each traversal, we calculate the cumulative cost of visiting nodes and ensure that nodes are visited only once, except for returning to the starting point to complete the cycle. If all nodes have been visited and there is a path back to the starting point, the total cost of that cycle is calculated. We keep track of the minimum cost among all valid cycles, updating it whenever a smaller cost is found.
80
Time Complexity: O(n!), As for the first node there are n possibilities and for the second node there are n - 1 possibilities.
For n nodes time complexity = n * (n - 1) * . . . 1 = O(n!)
Auxiliary Space: O(n)