Write a C program for Depth-First-Search (DFS) in a Graph.

DFS(G):
	  for each u ∈ G.V
      u.color = white
      time = 0
	  for each u ∈ G.V
	  if u.color == white
	  DFS-Visit(G,u)

DFS-Visit(G,u):
	 u.d = ++time
	 u.color = gray
	 for each v ∈ G.Adj[u]
	 if v.color == white
	 DFS-Visit(G,v)
     u.color = black
	 u.f = ++time

#include <stdio.h>
#include <stdlib.h>

#define MAX_NODES 5

typedef struct Node {
    int value;
    int color;
    int d;
    int f;
} Node;

void DFS(Node graph[], int u, int *time) {
    graph[u].color = 1;
    graph[u].d = ++(*time);

    for (int i = 0; i < MAX_NODES; i++) {
        if (graph[u].color == 0 && graph[u].value != graph[i].value) {
            DFS(graph, i, time);
        }
    }

    graph[u].color = 2;
    graph[u].f = ++(*time);
}

int main() {
    Node graph[MAX_NODES] = {
        {0, 0, 0, 0},
        {1, 0, 0, 0},
        {2, 0, 0, 0},
        {3, 0, 0, 0},
        {4, 0, 0, 0}
    };

    int adjacencyMatrix[MAX_NODES][MAX_NODES] = {
        {0, 1, 1, 0, 0},
        {0, 0, 0, 1, 1},
        {0, 0, 0, 0, 1},
        {0, 0, 0, 0, 0},
        {0, 0, 0, 0, 0}
    };

    int time = 0;

    for (int i = 0; i < MAX_NODES; i++) {
        if (graph[i].color == 0) {
            DFS(graph, i, &time);
        }
    }

    printf("Node\tColor\tDiscovery Time\tFinish Time\n");
    for (int i = 0; i < MAX_NODES; i++) {
        printf("%d\t%d\t%d\t%d\n", graph[i].value, graph[i].color, graph[i].d, graph[i].f);
    }

    return 0;
}

Node	Color	Discovery Time	Finish Time
0	2	1	        2
1	2	3	        4
2	2	5	        6
3	2	7	        8
4	2	9	        10

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.