Last active
February 8, 2025 02:38
-
-
Save abelardojarab/cad47bd478414983636bd1dc6e3f53fb to your computer and use it in GitHub Desktop.
DFS and BFS Graph Traversal in C++
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
#include <unordered_map> | |
#include <vector> | |
#include <queue> | |
#include <stack> | |
#include <unordered_set> | |
class Graph { | |
private: | |
std::unordered_map<int, std::vector<int>> adjList; | |
public: | |
void addEdge(int u, int v) { | |
adjList[u].push_back(v); | |
adjList[v].push_back(u); | |
} | |
// Depth first search | |
void dfs(int start) { | |
std::unordered_set<int> visited; //track visited unordered_set | |
std::stack<int> stack; | |
stack.push(start); | |
while (!stack.empty()) { | |
int node = stack.top(); | |
stack.pop(); | |
if (visited.find(node) == visited.end()) { | |
visited.insert(node); | |
std::cout << "Visited: " << node << "\n"; | |
for (int neighbor : adjList[node]) { | |
if (visited.find(neighbor) == visited.end()) { | |
stack.push(neighbor); | |
} | |
} | |
} | |
} | |
} | |
// BFS | |
void bfs(int start) { | |
std::unordered_set<int> visited; | |
std::queue<int> queue; | |
queue.push(start); | |
visited.insert(start); | |
while (!queue.empty()) { | |
int node = queue.front(); | |
queue.pop(); | |
std::cout << "Visited: " << node << "\n"; | |
for (int neighbor : adjList[node]) { | |
if (visited.find(neighbor) == visited.end()) { | |
visited.insert(neighbor); | |
queue.push(neighbor); | |
} | |
} | |
} | |
} | |
}; | |
int main() { | |
Graph g; | |
// Add edges | |
g.addEdge(1, 2); | |
g.addEdge(1, 3); | |
g.addEdge(2, 4); | |
g.addEdge(3, 4); | |
g.addEdge(4, 5); | |
std::cout << "DFS Traversal:\n"; | |
g.dfs(1); // Start DFS from node 1 | |
std::cout << "\nBFS Traversal:\n"; | |
g.bfs(1); // Start BFS from node 1 | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment