Rotate your phone or change to desktop for better experience

Rotate your phone or change to desktop for better experience

4.write a program to implement DFs algorithm for a graph. || DAA

 #include <stdio.h> 

#include <stdbool.h> 

#define MAX_VERTICES 100 

typedef struct { 

int vertices[MAX_VERTICES]; 

int adjacencyMatrix[MAX_VERTICES][MAX_VERTICES]; 

int numVertices; 

} Graph; 

void initGraph(Graph* g, int numVertices) { 

g->numVertices = numVertices; 

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

g->vertices[i] = 0; 

for (int j = 0; j < numVertices; j++) { 

g->adjacencyMatrix[i][j] = 0; 

void addEdge(Graph* g, int start, int end) { 

g->adjacencyMatrix[start][end] = 1; 

g->adjacencyMatrix[end][start] = 1; 

void DFS(Graph* g, int startVertex, bool visited[]) { 

visited[startVertex] = true; 

printf("%d ", startVertex); 

for (int i = 0; i < g->numVertices; i++) { 

if (g->adjacencyMatrix[startVertex][i] == 1 && !visited[i]) 

{ DFS(g, i, visited); 

void performDFS(Graph* g, int startVertex) { 

bool visited[MAX_VERTICES] = {false}; 

printf("DFS traversal starting from vertex %d: ", startVertex);  

DFS(g, startVertex, visited); 

int main() { Graph g; 

int numVertices, startVertex; 

printf("Enter the number of vertices: "); 

scanf("%d", &numVertices); 

initGraph(&g, numVertices); 

printf("Enter the adjacency matrix:\n"); 

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

for (int j = 0; j < numVertices; j++) { 

scanf("%d", &g.adjacencyMatrix[i][j]); 

printf("Enter the starting vertex for DFS: "); 

scanf("%d", &startVertex); 

performDFS(&g, startVertex); 

return 0; 

Post a Comment

0 Comments