0

I was trying to solve the travel salesman program im stuck at the recursive part of moving from one city to another.

Sample input & output:

    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

Main Objective

each number at the matrice roads[N][N] (currently N=4) is the distance as following: location (i,j) the number represents distance from city i to city j. and the objective is to get from city number 0 (line 0 in matrice) through all cities back to city 0 at shortest path.

My Solution Create a shell function ShortestFullPath() with all first parameters. and seconed backtracking function short_path where i check stopping conditions (such as same city => 0 or no city => -1 or finished going through all cites)

A array visited is as the size of number of cities. each city I visit, I flag the matching index in the array as true or false, and check all options in the city to other cities.

Side Notes

checkvisited() checks if array visited is all true;

min() checks minimun between current_path and the best path so far.

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;
}
Elad Par
  • 1
  • 1

0 Answers0