Search code examples
cdebugginggraphcycle

error code for travelling salesperson i.e finding cycle with minimum cost of a graph


    #include <stdio.h>
    int a[10][10],visited[10],n,cost=0;
    void mincost(int city)
    {
        int i,ncity;   //ncity==nearest city
        visited[city]=1;
        printf("%d->",city+1);
        ncity=least(city);
        if(ncity==999)  //no nearest city,hence back to 1
        {
            ncity=0;
            printf("%d",ncity+1);
            cost+=a[city][ncity];
            return;
        }
        mincost(ncity);   //recursive
    }
    int least(int c)
    {
        int i,nc=999;
        int min=999,kmin;
        for(i=0;i<n;i++)
        {
            if((a[c][i]!=0) && visited[i]==0)
            {
                if(a[c][i]<min)
                {
                    min=a[i][0]+a[c][i];
                    kmin=a[c][i];
                    nc=i;
                }
            }
        }
        if(min!=999)
            cost+=kmin;
        return nc;
    }
    int main()
    {
        int n,i,j;
        printf("Enter the number of cities:");
        scanf("%d",&n);
        printf("\nEnter the cost matrix:");
        for(i=0;i<n;i++)
        {
            for(j=0;j<n;j++)
            {
                scanf("%d",&a[i][j]);
            }
        }
        for(i=0;i<n;i++)
            visited[i]=0;
        printf("\nThe minimum path is:\n");
        mincost(0);
        printf("\nMinimum cost:%d",cost);
        getch();
        return 0;
    }

The program finds the cycle with least cost for a given graph. The function least finds the next nearest city denoted by nc & each city is considered one by one by recursively calling mincost function. The output is always the the first city & it's cost,that's it. Please help!


Solution

  • You have a global variable n which gets initialized to zero by the compiler. Then in the main function you have a local variable n that shadows the global variable, so when you read input from the user and initialize n to that, it's only the local variable which is initialized ad not the global which will still be zero.

    General tip: Avoid global variables. If you need other functions to know about a value or variable, then pass it as an argument.