I have a file containing a number N in first line then a matrix of NxN in the upcoming lines. What I have to do is to find the minimum distance between 2 given points. This could be a graph and I must find the distance between 2 nodes. Input file has it's content:
4
0 3 4 0
3 0 0 2
4 0 0 3
0 2 3 0
My code is:
#include <stdio.h>
FILE *file_in;
int n,first,last,a[50][50], st[50];
void read_matrix(int n)
{
int i,j;
for(i=0; i<n; i++)
{
for(j=0; j<n; j++)
{
fscanf(file_in,"%d",&a[i][j]);
}
}
}
void print_sol(int k)
{
int i;
printf("Solution is: ");
for(i=0; i<=k; i++)
printf("%d ", st[i]);
printf("\n");
}
int validation(k)
{
int i;
for(i=0; i<k; i++)
{
if(st[i]==st[k])
return 0;
}
if(!a[st[k-1]][st[k]])
return 0;
return 1;
}
int solution(k)
{
if(st[k]==last)
return 1;
else return 0;
}
void backtracking(int k)
{
int i;
if(k==n+1)
return;
else
{
for(i=0; i<n; i++)
{
st[k]=i;
if(validation(k))
{
if(solution(k))
print_sol(k);
else backtracking(k+1);
}
}
}
}
int main()
{
file_in=fopen("fis.txt", "r");
fscanf(file_in,"%d", &n);
read_matrix(n);
scanf("%d%d", &first, &last);
st[0]=first;
backtracking(1);
return 13;
}
After running this I get:
Solution is: 1 0 2
Solution is: 1 3 2
This code will print all solutions but what I need is to print only one, the one that has the minimum distance between first and last point, and I don't have any idea how to do this.
What I want to be printed is:
Solution is: 1 0 2
Thanks!