马上就要放寒假了,蒜头君已经辛勤的工作一年了,打算和家人一起出去旅游放松放松。有经验的人一定知道,出去旅游前一定要有详细的旅行规划。蒜头君打算旅游 n 个城市,但并不是每条路线的花费都是一样的。蒜头君是一个勤俭节俭的人,他就在想怎么把所有的城市旅游一遍花费最小呢?(蒜头君不喜欢重复旅游同一个城市,也就是说已到达过的城市蒜头君是不会再次光临的)
输入格式
第一行输入一个整数 n (1≤n≤15),表示有 n 个城市。
接下来有一个 n×n 的矩形,表示每两个城市之间的火车花费,每两个城市之间的花费不会超过 10000。
输出格式
输出一个整数,表示从 1 号城市把所有景点旅游一遍并且回到 1 号城市的最小花费。
样例输入
4
0 1 1 1
1 0 2 1
5 5 0 6
1 1 3 0
样例输出
8
//蒜头君的旅游计划
#include<iostream>
using namespace std;
int n;
int u, sum, cnt;
int ans = 100000;
int graph[20][20];
bool vis[20];
//求旅游n个城市的最小花费
void dfs(int u, int cnt, int sum) {
if (cnt == n && (sum + graph[u][1]<=ans)) {
ans = sum + graph[u][1];
cout << u << 1 << endl;
cout << endl;
return;
}
vis[u] = true;
for (int i = 1; i <= n; i++) {
if (vis[i]==false) {
cout << u << i << endl;
dfs(i, cnt+1, sum + graph[u][i]);
}
}
vis[u] = false;
}
int main() {
cin >> n;
for (int i = 1; i <= n; i++) {
vis[i] = false;
for (int j = 1; j <= n; j++) {
cin >> graph[i][j];
}
}
dfs(1, 1, 0);
cout << "ans:" << ans << endl;
return 0;
}
当dfs函数中if语句只有 cnt==n时 输出 全部解例如 10,8,10,9
void dfs(int u, int cnt, int sum) {
if (cnt == n ) {
ans = sum + graph[u][1];
cout << u << 1 << endl;
cout << ans << endl;
cout << endl;
return;
}