fork download
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <stdbool.h>
  4. #define MAX 100
  5. // Adjacency matrix for graph representation
  6. int graph[MAX][MAX];
  7. bool visited[MAX];
  8. int queue[MAX], front = -1, rear = -1;
  9.  
  10. // Function to add an edge to the graph
  11. void addEdge(int u, int v) {
  12. graph[u][v] = 1; // For directed graph
  13. graph[v][u] = 1; // Uncomment for undirected graph
  14. }
  15.  
  16. // Function for DFS traversal
  17. void dfs(int node, int vertices) {
  18. printf("%d ", node);
  19. visited[node] = true;
  20. for (int i = 0; i < vertices; i++) {
  21. if (graph[node][i] && !visited[i]) {
  22. dfs(i, vertices);
  23. }
  24. }
  25. }
  26.  
  27. // Function to enqueue for BFS
  28. void enqueue(int value) {
  29. if (rear == MAX - 1) return;
  30. if (front == -1) front = 0;
  31. queue[++rear] = value;
  32. }
  33.  
  34. // Function to dequeue for BFS
  35. int dequeue() {
  36. if (front == -1 || front > rear) return -1;
  37. return queue[front++];
  38. }
  39.  
  40. // Function for BFS traversal
  41. void bfs(int start, int vertices) {
  42. for (int i = 0; i < vertices; i++) visited[i] = false;
  43. enqueue(start);
  44. visited[start] = true;
  45. while (front <= rear) {
  46. int node = dequeue();
  47. printf("%d ", node);
  48. for (int i = 0; i < vertices; i++) {
  49. if (graph[node][i] && !visited[i]) {
  50. enqueue(i);
  51. visited[i] = true;
  52. }
  53. }
  54. }
  55. }
  56.  
  57. // Main function
  58. int main() {
  59. int vertices = 5;
  60.  
  61. // Initialize graph
  62. for (int i = 0; i < MAX; i++) {
  63. for (int j = 0; j < MAX; j++) {
  64. graph[i][j] = 0;
  65. }
  66. }
  67.  
  68. // Initialize visited array
  69. for (int i = 0; i < MAX; i++) {
  70. visited[i] = false;
  71. }
  72.  
  73. // Adding edges
  74. addEdge(0, 1);
  75. addEdge(0, 2);
  76. addEdge(1, 3);
  77. addEdge(1, 4);
  78.  
  79. printf("DFS Traversal starting from node 0:\n");
  80. dfs(0, vertices);
  81.  
  82. printf("\n\nBFS Traversal starting from node 0:\n");
  83. bfs(0, vertices);
  84.  
  85. return 0;
  86. }
  87.  
Success #stdin #stdout 0s 5284KB
stdin
10
aba
geeksforgeeks
geeksforgeeks
geeksforgeeks
geeksforgeeks
geeksforgeeks
geeksforgeeks
geeksforgeeks
geeksforgeeks
geeksforgeeks
stdout
DFS Traversal starting from node 0:
0 1 3 4 2 

BFS Traversal starting from node 0:
0 1 2 3 4