#include <iostream>
#include <stdlib.h>
#include <queue>
#include <stack>
#include <fstream>
#include <iomanip> // 本文用于输出对齐
using namespace std;
const int max_vexNum = 20;
bool is_visited[max_vexNum];
int path_num = 0;
int bestLength = 10000000;
int path_index = 0;
int path_DFS[max_vexNum][max_vexNum];
double lenth_DFS[max_vexNum];
typedef struct {
int vex_num, arc_num; // 顶点数 边数
double arcs[max_vexNum][max_vexNum]; // 邻接矩阵
}Graph;
int _findCityIndex(Graph G, int city_start) {
for (int i = 0; i < G.vex_num; i++)
{
if (i== city_start)
{
return i;
}
}
cout << "【error】当前城市未找到!" << endl;
return -1;
}
void DFS(Graph G, int city_start) {
int v_index = _findCityIndex(G, city_start); // 起始城市,每次调用(递归)都更新.
if (path_index == G.vex_num - 1 && G.arcs[v_index][0] > 0)
{
path_DFS[path_num][path_index] = city_start;
path_DFS[path_num][path_index + 1] = 0; // A为起始城市
lenth_DFS[path_num] = 0; // 存储最短路径
// 计算最短路径
for (int i = 0; i < G.vex_num; i++)
{
lenth_DFS[path_num] += G.arcs[path_DFS[path_num][i] ][path_DFS[path_num][i + 1] ];
}
if (bestLength > lenth_DFS[path_num])
{
// 更新最短路径
bestLength = lenth_DFS[path_num];
}
cout << "第【" << (path_num + 1) << "】条路径" << endl;
for (int i = 0; i < G.vex_num; i++)
cout << path_DFS[path_num][i] << "->";
cout<<"0"<< endl;
path_num++; // 下一条路径
// 初始化下一次路径与上一次相同
for (int i = 0; i < G.vex_num; i++)
{
path_DFS[path_num][i] = path_DFS[path_num - 1][i];
}
return;
}
else
{
for (int i = 0; i < G.vex_num; i++)
{
if (G.arcs[v_index][i] > 0 && !is_visited[i])
{
path_DFS[path_num][path_index] = city_start;
path_index++;
is_visited[v_index] = true;
DFS(G, i );
path_index--;
is_visited[v_index] = false;
}
}
}
}
int main() {
Graph G ;
cout << "tsp问题蛮力法..." << endl;
cout << "多少个城市:" << endl;
cin >> G.vex_num;
cout << "多少条路径" << endl;
cin >> G.arc_num;
cout << "路径起点终点,路径长度" << endl;
for (int i = 0; i < G.arc_num; i++) {
int a, b, c;
cin >> a >> b >> c;
G.arcs[a][b] = c;
G.arcs[b][a] = c;
G.arcs[i][i] = 0;
}
for (int i = 0; i < G.vex_num; i++)
{
for (int j = 0; j< G.vex_num; j++)
cout << G.arcs[i][j] << " ";
cout<< endl;
}
for (int i = 0; i < G.vex_num; i++)
{
is_visited[i] = false;
}
cout << "开始城市是-0" << endl;
int city_start=0;
time_t T_begin = clock();
DFS(G, city_start);
for (int i = 0; i < path_num; i++)
{
for (int j = 0; j <= G.vex_num; j++)
{
// cout<<path_DFS[i][j]<<" ";
// DFS_fout<<path_DFS[i][j]<<" ";
}
// cout<<"对应的路程lenth_DFS[] = "<<lenth_DFS[i]<<endl;
// DFS_fout<<"对应的路程lenth_DFS[] = "<<lenth_DFS[i]<<endl;
}
// DFS_fout<<"最短路程bestLength = "<<bestLength<<endl;
cout << "最短路程bestLength = " << bestLength << endl;
time_t T_end = clock();
double RunningTime = double(T_end - T_begin) / CLOCKS_PER_SEC;
// DFS_fout<<"程序运行时间 RunningTime = "<<RunningTime<<endl;
cout << "程序运行时间 RunningTime = " << RunningTime << endl;
system("pause");
return 0;
}