Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 3

Assignment-2

Problem statement- Write a C program for DFS Algorithm.

ALGORITHM:

 INPUT:- Entering the number of vertices in the graph,the adjacency matrix of the
graph and the starting vertex for the BFS traversal.

 OUTPUT:- Getting the order of vertices visited during the BFS traversal.

 PROCESS:-
Step 1: start.

Step 2: Initialize an array ‘visited’ of size 7 to keep track of visited nodes.

Step 3: initialize the adjacency matrix graph[7][7] according to the input graph .

Step 4: define a recursive function DFS with parameter i as input .

Step 5: print the current node i .

Step 6: mark node i visited i.e,

Visited[i]=1

Step 7: initialize j=0.

Step 8: for j less than 7 do the following steps .

Step 8.1: check if graph[i][j] is true and node j is not visited i.e,

Graph[i][j]=1 and visited[j]=0.

Step 8.2: call DFS with input j as passing parameter .

[END OF IF ]

[END OF LOOP]

Step 9: declare a variable c and input starting node .

Step 10: call DFS with input c to start the traversal .

Step 11: display the traversal result

Step 12 : End

SOURCE CODE :
#include<stdio.h>

#include<stdlib.h>

int visited[7];

int graph[7][7]={

{0,1,1,1,0,0,0}

,{1,0,1,0,0,0,1}

,{1,1,0,1,0,1,0}

,{1,0,1,0,1,0,0}

,{0,0,0,1,0,0,0}

,{0,0,1,0,0,0,1}

,{0,1,0,0,0,1,0}

};

void DFS(int i)

printf("%d ",i);

visited[i]=1;

int j;

for(j=0;j<7;j++)

if(graph[i][j]==1 && !visited[j])

DFS(j);

}
}

int main()

int c;

printf("enter your starting node -");

scanf("%d",&c);

printf("traversal result is :");

DFS(c);

return 0;

OUTPUT:
1. enter your starting node - 0
traversal result is :0 1 2 3 4 5 6

2. enter your starting node - 4


traversal result is :4 3 0 1 2 5 6

You might also like