Advertisement
Shailrshah

Depth First Search

Nov 8th, 2013
118
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.01 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. struct node
  4. {
  5.   int vertex;
  6.   struct node *next;
  7. }*g[50];
  8. int visited[50]={0};
  9. void insert(int x, int y){
  10.     struct node *p,*q = (struct node *) malloc(sizeof(struct node));
  11.     q->vertex = y; q->next = NULL;
  12.     if(g[x] == NULL) g[x] = q;
  13.     else{
  14.         p = g[x];
  15.         while(p->next) p = p->next;
  16.         p->next = q;
  17.     }
  18. }
  19. void DFS(int i)
  20. {
  21.     struct node *p;
  22.     printf("%d  ", i);
  23.     p = g[i];
  24.     visited[i] = 1;
  25.     while(p != NULL){
  26.         i=p->vertex;
  27.         if(!visited[i]) DFS(i);
  28.         p = p->next;
  29.     }
  30. }
  31. int main()
  32. {
  33.     int i, x, y, edge, n;
  34.     printf("\nEnter number of vertices: ");
  35.     scanf("%d", &n);
  36.     for(i=0; i<n; i++) g[i]=NULL;
  37.     printf("\nEnter number of edges: ");
  38.     scanf("%d", &edge);
  39.     for(i=0;i<edge;i++){
  40.         printf("\nEnter an edge(u,v): ");
  41.         scanf("%d %d", &x,&y);
  42.         insert(x, y);
  43.         insert(y, x);
  44.     }
  45.     printf("\nEnter a value: ");
  46.     scanf("%d", &n);
  47.     DFS(n);
  48. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement