问题
I'm trying to implement an algorithm in c which finds MST using DFS. I've already found the DFS algortihm and i understand it pretty well. I also know that i should follow these steps to achieve my purpose :
1 Run DFS till you find an edge going backwards or DFS stopped. If stopped return G.
2 On the circle that is constructed by the backwards going edge find the heaviest edge and remove it from G.
3 Return to 1.
Here is the DFS code :
#include<stdio.h>
void DFS(int);
int G[10][10],visited[10],n; //n is no of vertices and graph is sorted in array G[10][10]
void main()
{
int i,j;
printf("Enter number of vertices:");
scanf("%d",&n);
//read the adjecency matrix
printf("\nEnter adjecency matrix of the graph:");
for(i=0;i<n;i++)
for(j=0;j<n;j++)
fscanf("%d",&G[i][j]);
//visited is initialized to zero
for(i=0;i<n;i++)
visited[i]=0;
DFS(0);
}
void DFS(int i)
{
int j;
printf("\n%d",i);
visited[i]=1; // éviter cycle
for(j=0;j<n;j++)
if(!visited[j]&&G[i][j]==1)
DFS(j);
}
I need your help to implement the full algorithm or at least some advices. That would be much appreciated. Thank's in advance.
回答1:
This sounds like homework, so I'll tell you how I would approach the problem.
First, modify your DFS implementation to use an explicit stack instead of recursion. Create a new array int stack[10];
and a variable int stacksize = 0;
. The idea is that stack[0], stack[1], ..., stack[stacksize-1]
will correspond to the arguments i
of the outermost active invocation of DFS
to the innermost. I'll leave the details a bit sketchy because I'm sure that there have been other question/answer pairs about this aspect.
Second, whenever the graph has an edge back to a visited vertex, scan from the top of the stack back to the visited vertex, looking for the heaviest edge. Once you find it, delete that edge by modifying G
. To restart the depth-first search, pop the stack until you pop one of the endpoints of the deleted edge. Each time you pop something, clear its visited flag. The depth-first search continues from here (a complete restart is not necessary because it would do the same thing up to here).
来源:https://stackoverflow.com/questions/27650579/find-minimum-spanning-tree-using-depth-first-search-in-c