Friday, 4 November 2016

Program 18 - DFS



#include <stdio.h>
int n, a[20][20], visited[20], stack[20], top = -1;
char name[20];
void DFS(int v) {
int i;
visited[v] = 1;
stack[++top] = v;
while(top != -1) {
v = stack[top--];
printf("%c -> ", name[v]);
for(i = 0; i < n; i++) {
if(a[v][i] == 1 && visited[i] == 0) {
// Note this step we add i not v
stack[++top] = i;
visited[i] = 1;
}
}
}
}
int main() {
int i, j;
printf("Depth First Search 1.0:\n");
printf("Enter number of vertices: ");
scanf("%d", &n);
printf("Enter name of vertices: ");
for(i = 0; i < n; i++) {
// Note the space here
scanf(" %c", &name[i]);
}
for(i = 0; i < n; i++) {
visited[i] = 0;
}
printf("Enter adjacency matrix: \n");
for(i = 0; i < n; i++) {
for(j = 0; j < n; j++) {
scanf("%d", &a[i][j]);
}
}
for(i = 0; i < n; i++) {
if(visited[i] == 0) {
DFS(i);
}
}
}
































































































No comments:

Post a Comment