-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDFS.c
More file actions
68 lines (68 loc) · 1.52 KB
/
Copy pathDFS.c
File metadata and controls
68 lines (68 loc) · 1.52 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
#include <stdio.h>
#include <stdlib.h>
typedef struct node
{
int vert;
struct node* next;
}node;
typedef struct graph
{
int numvertices;
node** adjlist;
int *visited;
}graph;
node* createNode(int v)
{
node* NewNode=malloc(sizeof(node));
NewNode->vert=v;
NewNode->next=NULL;
return NewNode;
}
graph* createGraph(int verticies)
{
graph* NewGraph=malloc(sizeof(graph));
NewGraph->numvertices=verticies;
NewGraph->adjlist=malloc(verticies*sizeof(node *));
NewGraph->visited = malloc(verticies*sizeof(int));
for(int i=0;i<verticies;i++)
{
NewGraph->adjlist[i]=NULL;
NewGraph->visited[i]=0;
}
return NewGraph;
}
void Add(graph* graph,int s,int d)
{
node* newNode = createNode(d);
newNode->next = graph->adjlist[s];
graph->adjlist[s] = newNode;
newNode = createNode(s);
newNode->next = graph->adjlist[d];
graph->adjlist[d] = newNode;
}
void dfs(graph* graph,int vertex)
{
node* adjList = graph->adjlist[vertex];
node* temp = adjList;
graph->visited[vertex] = 1;
printf("Visited %d \n", vertex);
while(temp)
{
int connectedVertex = temp->vert;
if (graph->visited[connectedVertex] == 0)
{
dfs(graph, connectedVertex);
}
temp = temp->next;
}
}
int main(void)
{
graph* graph=createGraph(5);
Add(graph,0,1);
Add(graph,0,2);
Add(graph,0,3);
Add(graph,1,2);
Add(graph,2,4);
dfs(graph,0);
}