[英]DFS traversal in directed graph in C
我正在嘗試打印一個從vertex 0
開始的圖遍歷,它覆蓋了所有節點,並且應該在“定向到”之前訪問“定向自”頂點。 我在下面用預期的輸出解釋了我的問題。 這是代碼,
#include<stdio.h>
#include<stdlib.h>
typedef struct node
{
struct node *next;
int vertex;
}node;
node *G[20];
//heads of linked list
int visited[20];
int n;
void read_graph();
//create adjacency list
void insert(int,int);
//insert an edge (vi,vj) in te adjacency list
void DFS(int);
void main()
{
int i;
read_graph();
//initialised visited to 0
for(i=0;i<n;i++)
visited[i]=0;
DFS(0);
}
void DFS(int i)
{
node *p;
printf("\n%d",i);
p=G[i];
visited[i]=1;
while(p!=NULL)
{
i=p->vertex;
if(!visited[i])
DFS(i);
p=p->next;
}
}
void read_graph()
{
int i,vi,vj,no_of_edges;
printf("Enter number of vertices:");
scanf("%d",&n);
//initialise G[] with a null
for(i=0;i<n;i++)
{
G[i]=NULL;
//read edges and insert them in G[]
printf("Enter number of edges:");
scanf("%d",&no_of_edges);
for(i=0;i<no_of_edges;i++)
{
printf("Enter an edge(u,v):");
scanf("%d%d",&vi,&vj);
insert(vi,vj);
}
}
}
void insert(int vi,int vj)
{
node *p,*q;
//acquire memory for the new node
q=(node*)malloc(sizeof(node));
q->vertex=vj;
q->next=NULL;
//insert the node in the linked list number vi
if(G[vi]==NULL)
G[vi]=q;
else
{
//go to end of the linked list
p=G[vi];
while(p->next!=NULL)
p=p->next;
p->next=q;
}
}
它遍歷所有節點,輸出:-
Enter the number of vertices : 6
Enter the number of edges : 6
Enter an edge (u, v) :- 0 1
Enter an edge (u, v) :- 1 2
Enter an edge (u, v) :- 0 4
Enter an edge (u, v) :- 4 5
Enter an edge (u, v) :- 2 3
Enter an edge (u, v) :- 5 3
It is giving output :- 0 1 2 3 4 5
但是,如果我們仔細觀察, (u, v) = (2, 3)
和(u, v) = (5, 3)
我們會在 5 之前訪問 3。5 也指向 3。我的預期輸出應該是:- 0 4 5 1 2 3
我們訪問每個頂點並且在v
之前訪問u
我只懂 C,更喜歡 C 語言的解決方案。
根據我的說法,您的代碼實現是正確的,基本上您的圖形如下
0 -> 1 -> 2 -> 3
\ /
4 -------> 5
所以你的 0,1,2,3,4,5 輸出也是 DFS 方法的正確輸出,但如果你特別希望你的解決方案是 0,4,5,1,2,3 -> 那么你的輸入順序設置有向圖應采用這種格式
Enter the number of vertices : 6
Enter the number of edges : 6
Enter an edge (u, v) :- 0 4
Enter an edge (u, v) :- 4 5
Enter an edge (u, v) :- 0 1
Enter an edge (u, v) :- 1 2
Enter an edge (u, v) :- 2 3
Enter an edge (u, v) :- 5 3
It should give output as 0,4,5,1,2,3
希望這可以幫助!
您使用了錯誤的工具。 深度優先搜索不一定參觀“從導演的”前“指向”。
這是一個可以完成這項工作的算法:
首先,使用 DFS(或任何其他搜索)構建從起始頂點可到達的頂點列表。 默默地做這件事,什么也不打印。
然后在列表中找到一個頂點V,使得從列表中的一個頂點到V沒有邊,打印V,並從列表中刪除V。 重復此步驟直到列表為空。
保持邊關系的全序稱為拓撲排序。 您可以使用 DFS 獲得拓撲排序,該 DFS 以post-order訪問所有頂點。 但是后序與您想要的相反。
您的代碼按預先順序訪問節點:它在訪問其子節點之前打印每個節點。 因此,將printf
移到搜索兒童之后的位置。
打印順序的反面將具有您想要的屬性。
例如,如果您需要打印正確的順序,則可以在訪問節點時將節點推送到堆棧上。 搜索完成后,彈出並打印,直到棧為空。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.