Graph-DFS


Learn Theory - DFS

DFS Implementation using a recursive function
/*******************************************************************************/
#include <stdio.h>

#define MAX_VERTICES 10

// Function to perform Depth-First Search (DFS)
void dfs(int vertex, int visited[MAX_VERTICES], int adjacencyMatrix[MAX_VERTICES][MAX_VERTICES], int numVertices) {
    printf("V%d ", vertex ); // Assuming vertex labels are 'V0', 'V1', 'V2', ...

    // Mark the current vertex as visited
    visited[vertex] = 1;

    // Recursively visit all unvisited neighbors
    for (int i = 0; i < numVertices; i++) {
        if (adjacencyMatrix[vertex][i] == 1 && !visited[i]) {
            dfs(i, visited, adjacencyMatrix, numVertices);
        }
    }
}

int main() {
    int numVertices, i, j;

    printf("Enter the number of vertices (max %d): ", MAX_VERTICES);
    scanf("%d", &numVertices);

    // Input the adjacency matrix
    int adjacencyMatrix[MAX_VERTICES][MAX_VERTICES];
    printf("Enter the adjacency matrix (1 for connected, 0 for not connected):\n");
    for (i = 0; i < numVertices; i++) {
        for (j = 0; j < numVertices; j++) {
            scanf("%d", &adjacencyMatrix[i][j]);
        }
    }

    // Array to keep track of visited vertices
    int visited[MAX_VERTICES] = {0};

    // Perform DFS starting from each unvisited vertex
    printf("DFS Traversal Order:\n");
    for (i = 0; i < numVertices; i++) {
        if (!visited[i]) {
            dfs(i, visited, adjacencyMatrix, numVertices);
        }
    }

    return 0;
}


/* *******************DFS non recursive implementation using stack *************/
#include <stdio.h>
struct vertex{
int num;
int visit;
}S[50],v[50],t;

int adj[50][50],n,top=-1;
void push(struct vertex v)
{
top++;
S[top]=v;
}

struct vertex pop()
{
return(S[top--]);
}

int sempty()
{
if(top==-1) return 1;else return 0;
}

void dfs()
{ int i;
push(v[1]);v[1].visit=1;
while(!sempty())
{
t=pop();
printf("V%d-------->",t.num);
for(i=n;i>=1;i--) if(adj[t.num][i]==1 && v[i].visit==0) {push(v[i]);v[i].visit=1;}
}
}
void read()
{ int ad,i;
    printf("Enter the Number of vertices\n");
    scanf("%d",&n);
// storing element from [1][1]
//// assuming the vertices are numbered v1 v2..vn and we will enter only the index 1,2...n
    for(i=1;i<=n;i++) {v[i].num=i;v[i].visit=0;}
    for(i=1;i<=n;i++)
    {
        printf("Enter the list of vertices adjacent to v%d -1 to stop\n",i);
    while(1)
    {
        scanf("%d",&ad);
        if(ad==-1) break;
        adj[i][ad]=1;
    }
    }
}//end of read
void disp()
{
printf("Adjacency Matrix..\n");
for(int i=1;i<=n;i++)
{
for(int j=1;j<=n;j++)
printf("%5d",adj[i][j]);
printf("\n");
}
}
int main()
{
read();
disp();
printf("Depth First Search Result\n");
dfs();
return 0;
}

Comments

Popular posts from this blog

Data Structure Lab CSL 201 Manual KTU - Dr Binu V P-9847390760

Singly Linked List Implementation

Binary search Tree Implementation and Traversal