0% found this document useful (0 votes)
27 views2 pages

Depth First Search

This document contains a C program that implements Depth First Search (DFS) for a graph represented by an adjacency matrix. It includes functions to initialize visited vertices, perform the DFS traversal, and output the traversal starting from a specified vertex. The program prompts the user to input the number of vertices, the adjacency matrix, and the starting vertex for the DFS.

Uploaded by

swetha.v
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
27 views2 pages

Depth First Search

This document contains a C program that implements Depth First Search (DFS) for a graph represented by an adjacency matrix. It includes functions to initialize visited vertices, perform the DFS traversal, and output the traversal starting from a specified vertex. The program prompts the user to input the number of vertices, the adjacency matrix, and the starting vertex for the DFS.

Uploaded by

swetha.v
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 2

#include <stdio.

h>
#include <stdbool.h>

#define MAX 100 // Maximum number of vertices

// Function prototypes
void DFSUtil(int graph[MAX][MAX], int vertex, bool visited[], int numVertices);
void initializeVisited(bool visited[], int numVertices);

// Function to perform DFS


void DFS(int graph[MAX][MAX], int startVertex, int numVertices) {
bool visited[MAX]; // Track visited vertices
initializeVisited(visited, numVertices);

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


DFSUtil(graph, startVertex, visited, numVertices);
printf("\n");
}

// Utility function for DFS


void DFSUtil(int graph[MAX][MAX], int vertex, bool visited[], int numVertices) {
visited[vertex] = true;
printf("%d ", vertex);

// Visit all adjacent vertices


for (int i = 0; i < numVertices; i++) {
if (graph[vertex][i] == 1 && !visited[i]) {
DFSUtil(graph, i, visited, numVertices);
}
}
}

// Initialize the visited array to false


void initializeVisited(bool visited[], int numVertices) {
for (int i = 0; i < numVertices; i++) {
visited[i] = false;
}
}

int main() {
int graph[MAX][MAX];
int numVertices;
int startVertex;

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


scanf("%d", &numVertices);

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


for (int i = 0; i < numVertices; i++) {
for (int j = 0; j < numVertices; j++) {
scanf("%d", &graph[i][j]);
}
}

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


scanf("%d", &startVertex);

DFS(graph, startVertex, numVertices);


return 0;
}

You might also like