SHARE
TWEET

Untitled

a guest Apr 19th, 2019 90 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3.  
  4. #define MAX_NODES 100
  5.  
  6. typedef struct _adjlist {
  7.      int node;
  8.      struct _adjlist *link;
  9. } adjlist;
  10.  
  11. adjlist graph[MAX_NODES];
  12.  
  13. int visited[MAX_NODES];    // 0:unvisited    1:visited
  14.  
  15. void insert(int v1, int v2);
  16.  
  17. void dfs(int v);
  18.  
  19.  
  20.  
  21. void insert(int v1, int v2)
  22. {
  23.     adjlist* newNode = malloc(sizeof(struct _adjlist));
  24.     adjlist* tempNode = malloc(sizeof(struct _adjlist));
  25.    
  26.     newNode->node = v2;
  27.     newNode->link = NULL;
  28.    
  29.     if(graph[v1].link == NULL) graph[v1].link = newNode;
  30.     else {
  31.         tempNode = graph[v1].link;
  32.         while(tempNode->link != NULL) tempNode = tempNode->link;
  33.         tempNode->link = newNode;
  34.     }
  35. }
  36.  
  37. void dfs(int v)
  38. {
  39.     /*
  40.      Fill in your code here...
  41.      visit v and traverse all its edges recursively.
  42.      */
  43.     adjlist *w;
  44.     visited[v]= 1; printf("%d ",v);
  45.     for (w = graph[v].link; w != NULL; w = w->link){
  46.         if(visited[w->node] == 0){
  47.             dfs(w->node);
  48.         }
  49.     }
  50. }
  51.  
  52. int main()
  53. {
  54.     int m,a,b;
  55.    
  56.     // initialize
  57.     for(int i=0;i<MAX_NODES;i++)
  58.     {
  59.                 graph[i].link=NULL;
  60.                 visited[i]=0;  // unvisited
  61.     }
  62.  
  63.  
  64.     printf("Input the number of edges:\n");
  65.     scanf("%d",&m);
  66.     printf("Input these edges:\n");
  67.     for(int i=0; i<m; i++)
  68.     {
  69.         scanf("%d %d", &a, &b);
  70.         insert(a,b);
  71.           insert(b,a);
  72.     }
  73.     //dfs(0);
  74.     return 0;
  75. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top