forked from rafi007akhtar/c-algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdfs.c
More file actions
48 lines (36 loc) · 808 Bytes
/
dfs.c
File metadata and controls
48 lines (36 loc) · 808 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
// Perform Depth First Search on a given graph
#include <stdio.h>
#include <stdlib.h>
int n; // number of nodes in graph
int *visited; // array to keep a track of nodes visited
void dfs(int i, int g[n][n]);
int main()
{
int i, j, node;
printf("Enter the number of nodes: ");
scanf("%d", &n);
int g[n][n];
visited = (int *)calloc(n, sizeof(int));
printf("Enter the adjacency matrix of the graph:\n");
for (i = 0; i < n; i++)
{
for (j = 0; j < n; j++)
scanf("%d", &g[i][j]);
}
printf("Enter the source node: ");
scanf("%d", &node);
printf("\nThe nodes reachable from %d are:\n", node);
dfs(node-1, g);
return 0;
}
void dfs(int i, int g[n][n])
{
int j;
visited[i] = 1;
printf("%d ", i+1);
for (j = 0; j < n; j++)
{
if (!visited[j] && g[i][j] == 1)
dfs(j,g);
}
}