#include<stdio.h>
void DFS(int adj[20][20], int n, int visited[10], int u) {
int v, i;
for (v = 1; v <= n; v++) {
if (adj[u][v] == 1 && visited[v] == 0) {
visited[v] = 1;
printf("%d ", v);
DFS(adj, n, visited, v);
}
}
}
void main() {
int adj[30][20], n, visited[10], u, v, i, j;
printf("Enter no of vertices:");
scanf("%d", & n);
for (i = 1; i <= n; i++) {
for (j = 1; j <= n; j++) {
adj[i][j] = 0;
}
}
printf("Enter edge:");
scanf("%d%d", & u, & v);
while (u != 0) {
adj[u][v] = 1;
adj[v][u] = 1;
printf("Enter another edge:");
scanf("%d%d", & u, & v);
}
for (i = 1; i <= n; i++) {
visited[i] = 0;
}
printf("Enter starting vertex:");
scanf("%d", & u);
visited[u] = 1;
printf("%d ", u);
DFS(adj, n, visited, u);
}
Note: Need to be arranged in compiler after copied
OutPut:
Enter no of vertices:4
Enter edge:1 2
Enter another edge:1 3
Enter another edge:2 3
Enter another edge:3 1
Enter another edge:3 4
Enter another edge:4 4
Enter another edge:0 0
Enter starting vertex:2
2 1 3 4