這是C. DFS搜索的實現可以修改與重圖工作海事組織。
如果這是你在找什麼,我可以修改它與「多重圖」的工作。 。
#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++;
}
}
}
}
}
您在尋找什麼樣的輸出或返回值或結果? – joshlf
好像你可以使用某種遞歸回溯算法。沒有希望的節點將是那些已經訪問過的節點。 – nattyddubbs
@ joshlf13我編輯的問題,以示例輸出 – ekstrakt