Professional Documents
Culture Documents
Date :
AIM:
To implement a program for creating graph traversal using c.
GRAPH TRAVERSAL:
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
struct Node
int data;
};
struct Graph
int numVertices;
};
newNode->data=data;
newNode->next=NULL;
71762308204
return newNode;
graph->numVertices=numVertices;
for(int i=0;i<numVertices;++i)
graph->adjList[i]=NULL;
return graph;
newNode->next=graph->adjList[src];
graph->adjList[src]=newNode;
newNode=create(src);
newNode->next=graph->adjList[dest];
graph->adjList[dest]=newNode;
bool visited[MAX_VERTICES];
for(int i=0;i<graph->numVertices;++i)
71762308204
visited[i]=false;
int queue[MAX_VERTICES];
int front=-1,rear=-1;
visited[startVertex]=true;
queue[++rear]=startVertex;
while(front!=rear)
int currentVertex=queue[++front];
printf("%d ",currentVertex);
while(temp)
int adjVertex=temp->data;
if(!visited[adjVertex])
visited[adjVertex]=true; queue[+
+rear]=adjVertex;
temp=temp->next;
bool visited[MAX_VERTICES];
71762308204
for(int i=0;i<graph->numVertices;++i)
visited[i]=false;
int stack[MAX_VERTICES];
int top=-1;
stack[++top]=startVertex;
while(top!=-1)
int currentVertex=stack[top--];
if(!visited[currentVertex])
visited[currentVertex]=true;
printf("%d ",currentVertex);
while(temp)
int adjVertex=temp->data;
if(!visited[adjVertex])
stack[++top]=adjVertex;
71762308204
}
temp=temp->next;
int main()
add(graph,0,1);
add(graph,0,2);
add(graph,1,3);
add(graph,1,4);
int st;
scanf("%d",&st);
BFS(graph,st);
printf("\n");
DFS(graph,st);
printf("\n");
return 0;
71762308204
RESULT:
71762308204