File tree Expand file tree Collapse file tree 1 file changed +82
-0
lines changed Expand file tree Collapse file tree 1 file changed +82
-0
lines changed Original file line number Diff line number Diff line change 1+ #include <stdio.h>
2+ #include <stdlib.h>
3+
4+ //Structure for each vertex in graph
5+ struct node
6+ {
7+ int data ;
8+ struct node * next ;
9+ };
10+
11+ //Function to add node at the end of given root
12+ struct node * insert (struct node * root ,int d )
13+ {
14+ struct node * newPtr = (struct node * )malloc (sizeof (struct node ));
15+ newPtr -> data = d ;
16+ newPtr -> next = NULL ;
17+
18+ root -> next = newPtr ;
19+
20+ return newPtr ;
21+ }
22+
23+ //Function to perform DFS
24+ void explore (int node ,int vis [],struct node start [])
25+ {
26+ printf ("%d " ,node );
27+ vis [node ]= 1 ;
28+
29+ struct node * ptr = start [node ].next ;
30+
31+ for (;ptr != NULL ;ptr = ptr -> next )
32+ {
33+ if (vis [ptr -> data ]== 0 )
34+ {
35+ explore (ptr -> data ,vis ,start );
36+ }
37+ }
38+ }
39+
40+
41+ int main ()
42+ {
43+ int no_of_vertices = 7 ,i ,vis [8 ];
44+
45+ struct node start [8 ];
46+
47+ for (i = 1 ;i <=no_of_vertices ;i ++ )
48+ {
49+ start [i ].data = i ;
50+ start [i ].next = NULL ;
51+ vis [i ]= 0 ;
52+ }
53+
54+ /*
55+ Creates the following graph :
56+ 1
57+ / \
58+ 2 3
59+ / \ / \
60+ 4 5 6 7
61+ */
62+ struct node * cur ;
63+ cur = insert (& start [1 ],2 );
64+ insert (cur ,3 );
65+ cur = insert (& start [2 ],4 );
66+ insert (cur ,5 );
67+ cur = insert (& start [3 ],6 );
68+ insert (cur ,7 );
69+
70+ //The loop takes care of non connected graph also
71+ printf ("DFS of the graph : \n" );
72+ for (i = 1 ;i <=7 ;i ++ )
73+ {
74+ if (vis [i ]== 0 )
75+ explore (i ,vis ,start );
76+ }
77+
78+ return 0 ;
79+
80+
81+ // Output : 1 2 4 5 3 6 7
82+ }
You can’t perform that action at this time.
0 commit comments