Breadth


SUBMITTED BY: Guest

DATE: Dec. 10, 2013, 4:20 p.m.

FORMAT: Text only

SIZE: 2.1 kB

HITS: 804

  1. #include<iostream>
  2. #include<queue>
  3. #include<vector>
  4. #include<algorithm>
  5. using namespace std;
  6. struct adjlistnode{ int adj_node_val;
  7. adjlistnode *next;
  8. };
  9. struct adjlist{ adjlistnode*head;
  10. };
  11. struct grph{ int no_of_vertices;
  12. adjlist *array;
  13. };
  14. adjlistnode *create_new_adj_list_node(int val)
  15. {
  16. adjlistnode *t = new adjlistnode;
  17. t->adj_node_val = val;
  18. t->next = NULL;
  19. return t;
  20. }
  21. grph *create_grph(int v)
  22. {
  23. grph *t=new grph;
  24. t->no_of_vertices = v;
  25. t->array = new adjlist[v];
  26. for(int i=0;i<v;i++)
  27. {
  28. t->array[i].head = NULL;
  29. }
  30. return t;
  31. }
  32. void add_node(grph *t,int src,int des)
  33. {
  34. adjlistnode * temp = create_new_adj_list_node(des);
  35. temp->next = t->array[src].head;
  36. t->array[src].head = temp;
  37. /*
  38. adjlistnode * temp1 = create_new_adj_list_node(src);
  39. temp1->next = t->array[des].head;
  40. t->array[des].head = temp1;
  41. */
  42. cout<<" Edge created between "<<src<<" and "<<des<<endl;
  43. }
  44. void print_graph(grph *t)
  45. {
  46. for(int i=0;i<t->no_of_vertices;i++)
  47. {
  48. adjlistnode * temp = t->array[i].head;
  49. while(temp)
  50. {
  51. cout<<i<<"---------->"<<temp->adj_node_val<<endl;
  52. temp=temp->next;
  53. }
  54. }
  55. }
  56. void bfs(grph *t)
  57. {
  58. queue<int > q;
  59. vector<int> visited;
  60. q.push(0);
  61. visited.push_back(0);
  62. while(!q.empty())
  63. {
  64. int j = q.front();
  65. cout<<j<<endl;
  66. q.pop();
  67. adjlistnode* temp = t->array[j].head;
  68. while(temp)
  69. {
  70. int k=temp->adj_node_val;
  71. if(find(visited.begin(),visited.end(),k)==visited.end())
  72. {
  73. q.push(k);
  74. visited.push_back(k);
  75. }
  76. temp=temp->next;
  77. }
  78. }
  79. }
  80. int main()
  81. {
  82. grph * t = create_grph(5);
  83. add_node(t,0,3);
  84. add_node(t,2,3);
  85. add_node(t,1,2);
  86. add_node(t,3,4);
  87. add_node(t,0,1);
  88. bfs(t);
  89. print_graph(t);
  90. return 0;
  91. }

comments powered by Disqus