|
| 1 | +#include <iostream> |
| 2 | +#include <vector> |
| 3 | +#include <queue> |
| 4 | + |
| 5 | +using namespace std; |
| 6 | + |
| 7 | +// Graph class definition |
| 8 | +class Graph { |
| 9 | +public: |
| 10 | + vector<vector<int>> adjacencyList; |
| 11 | + |
| 12 | + // Constructor to initialize the adjacency list |
| 13 | + Graph(int totalNodes) { |
| 14 | + adjacencyList.resize(totalNodes); |
| 15 | + } |
| 16 | + |
| 17 | + // Function to add an edge to the graph |
| 18 | + void addEdge(int sourceNode, int destinationNode, bool isDirected = false) { |
| 19 | + adjacencyList[sourceNode].push_back(destinationNode); |
| 20 | + if (!isDirected) { |
| 21 | + adjacencyList[destinationNode].push_back(sourceNode); |
| 22 | + } |
| 23 | + } |
| 24 | + |
| 25 | + // Function to perform BFS traversal |
| 26 | + void bfs(int startNode) { |
| 27 | + vector<bool> visited(adjacencyList.size(), false); // Visited array |
| 28 | + queue<int> q; // Queue for BFS |
| 29 | + |
| 30 | + // Start BFS from the startNode |
| 31 | + visited[startNode] = true; |
| 32 | + q.push(startNode); |
| 33 | + |
| 34 | + cout << "BFS Traversal: "; |
| 35 | + |
| 36 | + while (!q.empty()) { |
| 37 | + int currentNode = q.front(); |
| 38 | + q.pop(); |
| 39 | + |
| 40 | + // Process the current node (e.g., print it) |
| 41 | + cout << currentNode << " "; |
| 42 | + |
| 43 | + // Visit all unvisited neighbors |
| 44 | + for (int neighbor : adjacencyList[currentNode]) { |
| 45 | + if (!visited[neighbor]) { |
| 46 | + visited[neighbor] = true; |
| 47 | + q.push(neighbor); |
| 48 | + } |
| 49 | + } |
| 50 | + } |
| 51 | + cout << endl; |
| 52 | + } |
| 53 | +}; |
| 54 | + |
| 55 | +int main() { |
| 56 | + int totalNodes = 6; |
| 57 | + |
| 58 | + // Create the graph |
| 59 | + Graph g(totalNodes); |
| 60 | + |
| 61 | + // Add edges to the graph |
| 62 | + g.addEdge(0, 1); |
| 63 | + g.addEdge(0, 2); |
| 64 | + g.addEdge(1, 3); |
| 65 | + g.addEdge(1, 4); |
| 66 | + g.addEdge(2, 5); |
| 67 | + |
| 68 | + // Perform BFS traversal starting from node 0 |
| 69 | + g.bfs(0); |
| 70 | + |
| 71 | + return 0; |
| 72 | +} |
0 commit comments