使用简单回溯解决方案的C中的TSP问题

时间:2019-01-15 18:36:21

标签: c backtracking traveling-salesman

我正试图解决停留在从一个城市到另一个城市的递归部分的旅行推销员计划。

示例输入和输出:

    Please enter the roads 4X4 matrix row by row:
    0 2 -1 2
    -1 0 2 -1
    1 -1 0 2
    2 1 -1 0
    The shortest path is of length: 6

主要目标

每条主要道路的数量[N] [N](当前N = 4) 距离如下: 位置(i,j),该数字表示从城市i到城市j的距离。 目标是从城市编号0(矩阵中的第0行)经过所有城市,以最短路径回到城市0。

我的解决方案 用所有第一个参数创建一个Shell函数ShortestFullPath()。 和第二个回溯功能short_path  我在哪里检查停车条件(例如同一城市=> 0或无城市=> -1或已遍历所有城市)

访问的数组与城市数量的大小相同。 我访问过的每个城市,都会将数组中匹配的索引标记为true或false,并检查该城市中其他城市的所有选项。

注释

checkvisited()检查访问的数组是否全部为真;

min()检查current_path和到目前为止的最佳路径之间的最小值。

int ShortestFullPath(int roads[N][N])


bool visited[N];
for(int i = 0; i < N; i++)
{
    visited[i] = false;
}
int shortest_path = 9999;
int current_path = 0;
int city = 0;
int j = 0; //destinaton city
visited [0] = true;
if(short_path(roads, city, j, current_path, &shortest_path, visited))
    Print(shortest_path);
else
    Print(NO_PATH);
return 0;



bool short_path(int roads[N][N], int city, int j, int current_path,
int *shortest_path, bool visited[N])
{

    if(check_visited(visited))
    {
        *(shortest_path) = min(current_path, *shortest_path);
        current_path = 0;
        return true;
    }
    if((roads[city][j] == -1) ||(roads[city][j] == 0)){
          return false;}
    if(visited[city] == true)
        return false;

    visited[city] = true;
    current_path = current_path + roads[city][j];


    for(int j =0; j< N; j++)
    {
        short_path(roads, city, j, current_path, shortest_path, visited);
    }
    visited[city] = false;
    return true;
}

0 个答案:

没有答案
相关问题