0

I've written a code, that gives the least cost for an array, which stores length of paths from each city to each city. I used recursion in my code. User chooses the first city from which the salesman begins his tour. The salesman has to visit each city once and come back to city which he started from. My code gives the correct cost, but I have no idea how to get the path, which gives that least cost. Should I use some extra arrays? I don't know when to add a city to the path. Any help?

void Dynamic::dynamic(Array array)
{
    int start;
    size = array.getSize();
    s = size;
    path = new int[size+1];
    
    
    
    cout << "Which city we start from?" << endl;
    cin >> start;
    int* cities = new int[size];
    for (int i=0; i<size+1; i++)
    {
        cities[i] = i;
        
    }
    
    
    
    int cost = g(array, size-1, cities, start, start, s);
    
    cout<<"Minimum cost: " << cost << endl;
    cout << "Path:" <<endl;
    
    for (int i=size; i>=0; i--)
    {
        cout << path[i] << "\t";
    }
    
    cout << "\n";
    
}

int Dynamic::g(Array & array, int level, int* tab, int city, int start, int z)
{
    if (level>0)
    {
        

        int minimum = INF;
        
        
        int position;
        bool exists = false;
        int k = z;
    
        for (int i=0; i<z; i++)
        {
            
            if (tab[i] == city)
            {
                position = i;
                exists = true;
            }
        }
        
        int* tmp;
        
    if (exists == true)
    
    {
        k = z-1;
        tmp = new int [k];
        for (int i=0; i<position; i++)
        {
            tmp[i] = tab[i];
        }
    
        for (int i=position; i<k; i++)
        {
            tmp[i] = tab[i+1];
        }
    }
    
    else
    {
        tmp = new int [k];
        for (int i=0; i<k; i++)
        {
            tmp[i] = tab[i];
        }
    }
    
        
        for (int i=0; i<k; i++)
        {
        
        
            
            int c = array[city][tmp[i]];
        
            int* t = new int [k-1];
            for(int j=0; j<i; j++)
            {
                t[j] = tmp[j];
            }           
            
            for (int j=i; j<k-1; j++)
            {
                t[j] = tmp[j+1];
            }
        
            
            int a = g(array, level-1, t, tmp[i], start, k-1);
            
            int result = c + a;
            
            if (minimum> result)
            {
                minimum = result;
                
                
                
            }
            
            
        }
        
        return minimum;
    }
    
    if (level == 0)
    {
        
        return array[city][start];
    }
}

czesiek
  • 3
  • 2

0 Answers0