You are on page 1of 7

Ex no : 9 GRAPHS

Date :

AIM:
To implement a program for creating graph traversal using c.

GRAPH TRAVERSAL:

#include <stdio.h>

#include <stdlib.h>

#include <stdbool.h>

#define MAX_VERTICES 100

struct Node

int data;

struct Node* next;

};

struct Graph

int numVertices;

struct Node* adjList[MAX_VERTICES];

};

struct Node* create(int data)

struct Node* newNode=(struct Node*)malloc(sizeof(struct Node));

newNode->data=data;

newNode->next=NULL;

71762308204
return newNode;

struct Graph* createGraph(int numVertices)

struct Graph* graph=(struct Graph*)malloc(sizeof(struct Graph));

graph->numVertices=numVertices;

for(int i=0;i<numVertices;++i)

graph->adjList[i]=NULL;

return graph;

void add(struct Graph* graph,int src,int dest)

struct Node* newNode=create(dest);

newNode->next=graph->adjList[src];

graph->adjList[src]=newNode;

newNode=create(src);

newNode->next=graph->adjList[dest];

graph->adjList[dest]=newNode;

void BFS(struct Graph* graph,int startVertex)

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);

struct Node* temp=graph->adjList[currentVertex];

while(temp)

int adjVertex=temp->data;

if(!visited[adjVertex])

visited[adjVertex]=true; queue[+

+rear]=adjVertex;

temp=temp->next;

void DFS(struct Graph* graph,int startVertex)

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);

struct Node* temp=graph->adjList[currentVertex];

while(temp)

int adjVertex=temp->data;

if(!visited[adjVertex])

stack[++top]=adjVertex;

71762308204
}

temp=temp->next;

int main()

struct Graph* graph=createGraph(5);

add(graph,0,1);

add(graph,0,2);

add(graph,1,3);

add(graph,1,4);

printf("ENTER THE STARTING VERTEX(0,1,2,3,4) :");

int st;

scanf("%d",&st);

printf("BFS TRAVERSAL STARTING FROM VERTEX %d: ",st);

BFS(graph,st);

printf("\n");

printf("DFS TRAVERSAL STARTING FROM VERTEX %d: ",st);

DFS(graph,st);

printf("\n");

return 0;

71762308204
RESULT:

Thus the program for graph traversal was implemented successfully.

71762308204

You might also like