/**
1891 · Travel Plan
Algorithms
Medium
Accepted Rate
60%
DescriptionSolutionNotesDiscussLeaderboard
Description
There are n cities, and the adjacency matrix arr represents the distance between any two cities.arr[i][j] represents the distance from city i to city j .Alice made a travel plan on the weekend. She started from city 0, then she traveled other cities 1 ~ n-1, and finally returned to city 0. Alice wants to know the minimum distance she needs to walk to complete the travel plan. Return this minimum distance. Except for city 0, every city can only pass once, and city 0 can only be the starting point and destination. Alice can’t pass city 0 during travel.
n<=10
arr[i][j]<=10000
Example
Example 1:
Input:
[[0,1,2],[1,0,2],[2,1,0]]
Output:
4
Explanation:
There are two possible plans.
The first, city 0-> city 1-> city 2-> city 0, cost = 5.
The second, city 0-> city 2-> city 1-> city 0, cost = 4.
Return 4
Example 2:
Input:
[[0,10000,2],[5,0,10000],[10000,4,0]]
Output:
11
Tags
https://blog.csdn.net/qq_46105170/article/details/110155730
https://www.lintcode.com/problem/1891/
*/
const INT_MAX = int(^uint(0) >> 1)
/**
* @param arr: the distance between any two cities
* @return: the minimum distance Alice needs to walk to complete the travel plan
*/
func travelPlan(arr [][]int) int {
// Write your code here.
if arr == nil || len(arr) == 0 {
return 0
}
var n int = len(arr)
var dp = make([][]int, 1<<uint8(n))
for i := 0; i < 1<<uint8(n); i++ {
dp[i] = make([]int, n)
}
for i := 0; i < (1<<uint8(n)); i++ {
for j := 0; j < n; j++ {
dp[i][j] = INT_MAX - 10000
}
}
dp[(1<<uint8(n))-1][0] = 0
for s := 1<<uint8(n) - 2; s >= 0; s-- {
for v := 0; v < n; v++ {
for u := 0; u < n; u++ {
if (s>>uint8(u))&1 == 0 {
dp[s][v] = Min(dp[s][v], dp[s|(1<<uint8(u))][u]+arr[v][u])
}
}
}
}
return dp[0][0]
}
func Min(a, b int) int {
if a < b {
return a
}
return b
}