Program:
#include<stdio.h> void DFS(int[20][20], int, int[20], int); int main() { int n, a[20][20], i, j, visited[20], source; printf("****************************************************************"); printf("\n****************************************************************"); printf("\n** Program for Depth First Search in C **"); printf("\n** Created by Sheetal Garg **"); printf("\n** Assistant Professor **"); printf("\n** Phone No:9467863365 **"); printf("\n****************************************************************"); printf("\n****************************************************************"); printf("\nEnter the number of vertices: "); scanf("%d", &n); printf("\nEnter the adjacency matrix:\n"); for (i = 1; i <= n; i++) for (j = 1; j <= n; j++) scanf("%d", &a[i][j]); for (i = 1; i <= n; i++) visited[i] = 0; printf("\nEnter the source node: "); scanf("%d", &source); DFS(a, source, visited, n); for (i = 1; i <= n; i++) { if (visited[i] == 0) { printf("\nGraph is not connected"); break; } } if(i>n) printf("\nGraph is connected\n"); return 0; } void DFS(int a[20][20], int u, int visited[20], int n) { int v; visited[u] = 1; for (v = 1; v <= n; v++) { if (a[u][v] == 1 && visited[v] == 0) DFS(a, v, visited, n); } }
OUTPUT 1
**************************************************************** **************************************************************** ** Program for Depth First Search in C ** ** Created by Sheetal Garg ** ** Assistant Professor ** ** Phone No:9467863365 ** **************************************************************** **************************************************************** Enter the number of vertices: 4 Enter the adjacency matrix: 1 1 1 0 1 0 0 1 1 0 0 1 1 0 1 0 Enter the source node: 1 Graph is connected
OUTPUT 2:
**************************************************************** **************************************************************** ** Program for Depth First Search in C ** ** Created by Sheetal Garg ** ** Assistant Professor ** ** Phone No:9467863365 ** **************************************************************** **************************************************************** Enter the number of vertices: 4 Enter the adjacency matrix: 1 1 0 1 1 1 0 0 1 0 1 1 1 1 0 1 Enter the source node: 2 Graph is not connected