Couldn't get the required correct output

65 Views Asked by At

I'm trying to solve the Hamiltonial cycle and path problem using backtracking method whether a source vertex is given for the input graph. When all the vertex are visited in that input graph, then the path will be displayed. Using backtracking approach, I want to get all the hamiltonaial path or cycle for the input graph.

This is my code:

#include<stdio.h>
#include<conio.h>
#include<stdbool.h>
int m=0;
int ans[5];

void Hamilton(int G[5][5], int visited[5], int n, int f){
    if(m == 5-1){
        for(int i=0;i<f;i++)
            printf("%d ",ans[i]);
        printf("\n");
        return;
    }
    else{
        visited[n] = n;
        m++;
        for(int i=0;i<5;i++){
            if(G[n][i] == 1){
                if(visited[i] == -1){
                     n = i;
                     ans[f++] = i;
                     Hamilton(G, visited, n, f);
                }           
            }
        }
        visited[n] = -1;
        m--;
        return;
    }
}

void main(){
    int G[5][5] = {
        {0,1,1,0,0},
        {1,0,0,1,1},
        {1,0,0,1,0},
        {0,1,1,0,1},
        {0,1,0,1,0}
    };
    int n = 0;
    int visited[5] = {-1,-1,-1,-1,-1};
    ans[0] = 0;
    Hamilton(G, visited, n, 1);
}

But in the output, nothing is showing in the output screen

1

There are 1 best solutions below

0
Armali On

One error is that by n = i; you overwrite the original vertex n, and due to this the resetting visited[n] = -1; later doesn't work. A second error is that f is only incremented and never decremented on backtracking. We can correct those two errors by changing

                     n = i;
                     ans[f++] = i;
                     Hamilton(G, visited, n, f);

to

                     ans[f] = i;
                     Hamilton(G, visited, i, f+1);

- still a remaining problem in the general case (not with cycle graphs as the given G) is that this Hamilton function only finds paths that start at vertex 0.