Graph DFS

PHOTO EMBED

Thu Oct 26 2023 17:34:07 GMT+0000 (Coordinated Universal Time)

Saved by @Astik

#include <stdio.h>
#include<conio.h>
int n,i,j;
int graph[20][20];
int visited[20];
void dfs(int node, int n) {
    printf("%d ", node);
    visited[node] = 1;
    for (i = 0; i < n; i++) {
	if (graph[node][i] && !visited[i]) {
	    dfs(i, n);
	}
    }
}

int main() {
    int start_node;
    printf("Enter the number of nodes(Less than 20): ");
    scanf("%d", &n);

    // for (int i = 0; i < n; i++) {
    //     visited[i] = 0;
    //     for (int j = 0; j < n; j++) {
    //         graph[i][j] = 0;
    //     }
    // }

    printf("Enter the adjacency matrix (0 or 1):\n");
    for (i = 0; i < n; i++) {
	for (j = 0; j < n; j++) {
	    printf("i=%d, j=%d Enter: ",i,j);
	    scanf("%d", &graph[i][j]);
	}
    }
    printf("Enter the starting node for DFS: ");
    scanf("%d", &start_node);

    printf("DFS traversal starting from node %d: ", start_node);
    dfs(start_node, n);
    printf("\n");
    getch();
    return 0;
}
content_copyCOPY