这是 C 中 DFS 搜索的实现。可以修改为与 MultiGraphs imo 一起使用。
如果这是您正在寻找的,我可以修改它以使用“MultiGraphs”..
#include <stdio.h>
#include <malloc.h>
#include <conio.h>
typedef struct AdjacencyList
{
char VertexID;
int *IncidenceList;
}AdjList;
typedef struct Graph
{
int VertexCount, Status;
char VertexName;
AdjList List;
struct Graph *Next;
}Graph;
Graph* InitializeGraph();
Graph *InitGraphNode(int cnt);
void PerformDepthFirstSearch(Graph *graph);
int main()
{
Graph *graph;
graph = InitializeGraph();
PerformDepthFirstSearch(graph);
return 0;
}
Graph *InitGraphNode(int cnt)
{
Graph *node = ((Graph*)malloc(sizeof(Graph)));
node->List.IncidenceList = ((int*)malloc(sizeof(int)*cnt));
node->Next = NULL;
return node;
}
Graph* InitializeGraph()
{
Graph *graphHead = NULL, *node, *tmp, *tmp2;
char vname;
int cnt, i, j, isIncident = 0;
printf("Enter the number of vertices : ");
scanf("%d", &cnt);
if (cnt == 0)
{
printf("Number of vertices cannot be ZERO!!\n\n");
return graphHead;
}
graphHead = InitGraphNode(1);
graphHead->VertexCount = cnt;
for(i = 0; i < cnt; i++)
{
printf("VertexName : ");
vname = getche();
printf("\n");
node = InitGraphNode(cnt);
node->VertexName = vname;
node->Next = NULL;
node->Status = 1;
if (graphHead->Next == NULL)
{
graphHead->Next = node;
}
else
{
tmp = graphHead;
while (tmp->Next != NULL)
{
tmp = tmp->Next;
}
tmp->Next = node;
}
}
tmp = graphHead->Next;
printf("Prepare to input the adjacent elements of corresponding vertices...\n\n");
for(i = 0; i < cnt; i++)
{
vname = tmp->VertexName;
tmp2 = graphHead->Next;
for(j = 0; j < cnt; j++)
{
here :
printf("%c incident on %c :: (1 for YES)(0 for NO) ::-> ",vname, tmp2->VertexName);
scanf("%d", &isIncident);
if ((isIncident < 0)||(isIncident > 1))
{
printf("Wrong Input!! Try again!!\n\n");
goto here;
}
tmp->List.IncidenceList[j] = isIncident;
tmp2 = tmp2->Next;
}
tmp = tmp->Next;
}
return graphHead;
}
void PerformDepthFirstSearch(Graph *graph)
{
Graph *Stack[100], *Copy = graph->Next, *node, *tmp = graph->Next;
int top = 0, i, cnt = 0;
Stack[top++] = Copy;
Copy->Status++;
while(top != 0)
{
node = Stack[--top];
node->Status++;
printf("%c, ", node->VertexName);
for(i = 0; i < graph->VertexCount; i++)
{
if(node->List.IncidenceList[i] == 1)
{
while (cnt < i)
{
tmp = tmp->Next;
cnt++;
}
if (tmp->Status == 1)
{
Stack[top++] = tmp;
tmp->Status++;
}
}
}
}
}