Advertisement
illeas

BFS using queue

Aug 2nd, 2019
145
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.48 KB | None | 0 0
  1. /*
  2. * CSE 2026 - Algorithms lab
  3. * Undirected BFS (Basic)
  4. */
  5.  
  6. #include <bits/stdc++.h>
  7.  
  8. using namespace std;
  9.  
  10. // Visited is a boolean. if visited[i] == true then node i is visited
  11. bool visited[1000];
  12.  
  13. int graph[100][100], nodes, edges;
  14.  
  15. void bfs(int source, int destination)
  16. {
  17. queue<int> q;
  18.  
  19. // Push source into queue and make it visited
  20. q.push(source);
  21. visited[source] = true;
  22.  
  23. printf("\n\nTraversing from source to destination: ");
  24. while (!q.empty()) // Keep looping until queue is empty
  25. {
  26.  
  27. int f = q.front();
  28. printf("%d ",f);
  29. q.pop();
  30.  
  31. // End loop if destination is traversed
  32. if(f == destination)
  33. {
  34. printf("\n");
  35. break;
  36. }
  37.  
  38. // Check all the nodes to see if it is connected with f
  39. for(int i=1; i<=nodes; i++)
  40. {
  41. // If f and i are connected and i is not visited then push i and make it visited
  42. if(graph[f][i] == 1 && visited[i] == false)
  43. {
  44. q.push(i);
  45. visited[i] = true;
  46. }
  47. }
  48. }
  49. }
  50. int main()
  51. {
  52. printf("Input number of Nodes and Edges: ");
  53. scanf("%d %d",&nodes,&edges);
  54.  
  55. int a, b, source, destination;
  56. printf("\nInput the edges: \n");
  57.  
  58.  
  59. /*
  60. * NOTE: If you input code to have 5 nodes in total. Node 1,2,3,4,5 is created.
  61. * So you have to input connection between these nodes only [1~5].
  62. * For example, if number of nodes is 5 then you cant connect 1 6 [Node 1 and 6] as node 6 has not been created.
  63. */
  64. for (int i = 1; i <= edges; i++)
  65. {
  66. scanf("%d %d",&a,&b);
  67.  
  68. // Making an undirected graph. if graph[a][b] has value of 1 means a and b are connected
  69. graph[a][b] = 1;
  70. graph[b][a] = 1; // If a and b is connected then we also need to connect b and a
  71. }
  72.  
  73. printf("\n\nInput source: ");
  74. scanf("%d",&source);
  75.  
  76. printf("\n\nInput destination: ");
  77. scanf("%d",&destination);
  78.  
  79. // Send source and destination to the function
  80. bfs(source, destination);
  81.  
  82. return 0;
  83. }
  84. /*
  85.  
  86. SAMPLE INPUT:
  87. 6 7 [6 is number of nodes 7 is number of edges]
  88.  
  89. // Input the connections: [Between node 1~6]
  90.  
  91. 1 2 // 1 and 2 are connected
  92. 2 4 // 2 and 4 are connected
  93. 1 3 // 1 and 3 are connected .... etc.
  94. 3 4
  95. 3 5
  96. 5 6
  97. 4 6
  98.  
  99. // Input source and destination
  100. 1 6
  101.  
  102. SAMPLE OUTPUT:
  103. Traversing from source to destination: 1 2 3 4 5 6
  104.  
  105. */
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement