fork download
  1. #include <iostream>
  2. #include <vector>
  3. #include <queue>
  4. #include <omp.h>
  5.  
  6. using namespace std;
  7.  
  8. // Function to perform Depth First Search (DFS)
  9. void dfs(vector<vector<int>>& graph, vector<bool>& visited, int node) {
  10. visited[node] = true;
  11. cout << node << " ";
  12.  
  13. #pragma omp parallel for
  14. for (int i = 0; i < graph[node].size(); ++i) {
  15. int next_node = graph[node][i];
  16. if (!visited[next_node]) {
  17. dfs(graph, visited, next_node);
  18. }
  19. }
  20. }
  21.  
  22. // Function to perform Breadth First Search (BFS)
  23. void bfs(vector<vector<int>>& graph, int start_node) {
  24. vector<bool> visited(graph.size(), false);
  25. queue<int> q;
  26. q.push(start_node);
  27. visited[start_node] = true;
  28.  
  29. while (!q.empty()) {
  30. int node = q.front();
  31. q.pop();
  32. cout << node << " ";
  33.  
  34. #pragma omp parallel for
  35. for (int i = 0; i < graph[node].size(); ++i) {
  36. int next_node = graph[node][i];
  37. if (!visited[next_node]) {
  38. visited[next_node] = true;
  39. q.push(next_node);
  40. }
  41. }
  42. }
  43. }
  44.  
  45. int main() {
  46. // Example undirected graph representation
  47. vector<vector<int>> graph = {
  48. {1, 2}, // Node 0
  49. {0, 3, 4}, // Node 1
  50. {0, 5}, // Node 2
  51. {1}, // Node 3
  52. {1}, // Node 4
  53. {2} // Node 5
  54. };
  55.  
  56. cout << "DFS traversal: ";
  57. vector<bool> visited_dfs(graph.size(), false);
  58. dfs(graph, visited_dfs, 0);
  59. cout << endl;
  60.  
  61. cout << "BFS traversal: ";
  62. bfs(graph, 0);
  63. cout << endl;
  64.  
  65. return 0;
  66. }
  67.  
Success #stdin #stdout 0s 5304KB
stdin
Standard input is empty
stdout
DFS traversal: 0 1 3 4 2 5 
BFS traversal: 0 1 2 3 4 5