Pages - Menu

Saturday, 4 May 2019

Implementation of Depth First Search DFS in C

HERE IS THE CODE..


#include<stdio.h>
#include<stdlib.h>
struct node {
    int data;
    struct node *next;
};
struct node *nodeList[20];
void dfs(int, int*);
void insert(int, int);
void main() {
    int numberOfVertices,numberOfEdges, i, j, v1, v2, visited[20];
    printf("Enter the number of vertices\n");
    scanf("%d", &numberOfVertices);
    for (i=0;i<=numberOfVertices;i++) {
        visited[i] = 0;
        nodeList[i]=NULL;
    }
    printf("Enter the number of edges\n");
    scanf("%d", &numberOfEdges);
    for (i=0;i<numberOfEdges;i++) {
        printf("Enter the edges\n");
        scanf("%d %d", &v1, &v2);
        insert(v1, v2);
    }
    dfs(1, visited);
}

// vertax is v1 and it points to v2 so add v2 in linked list of node v1
// ie. add v2 to nodeList[v1]
void insert(int v1, int v2) {
    struct node *temp2;
    struct node *temp = (struct node*)malloc(sizeof(struct node));
    temp->data = v2;
    temp->next = NULL;

    if (nodeList[v1]==NULL) {
        nodeList[v1] = temp;
    } else {
        temp2 = nodeList[v1];
        while(temp2->next != NULL) {
            temp2 = temp2->next;
        }
        temp2->next = temp;
    }
}

// start_node is the vertax from which dfs traversal starts
void dfs(int start_node, int *visited) {
    struct node *temp;
    if (visited[start_node] != 1) {
        printf("%d\t", start_node);
        visited[start_node] = 1;
    }
    temp = nodeList[start_node];
    while (temp != NULL) {
        if (visited[temp -> data] != 1) {
            dfs(temp->data, visited);
        }
        temp = temp->next;
    }
}

No comments:

Post a Comment