-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDepth-First Search (DFS) and Breadth-First Search (BFS).cpp
64 lines (51 loc) · 1.32 KB
/
Depth-First Search (DFS) and Breadth-First Search (BFS).cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
#include <iostream>
#include <vector>
#include <queue>
using namespace std;
void dfs(const vector<vector<int>>& graph, vector<bool>& visited, int node) {
visited[node] = true;
cout << node << " ";
for (int neighbor : graph[node]) {
if (!visited[neighbor]) {
dfs(graph, visited, neighbor);
}
}
}
void bfs(const vector<vector<int>>& graph, int start) {
int numNodes = graph.size();
vector<bool> visited(numNodes, false);
queue<int> q;
visited[start] = true;
q.push(start);
while (!q.empty()) {
int node = q.front();
q.pop();
cout << node << " ";
for (int neighbor : graph[node]) {
if (!visited[neighbor]) {
visited[neighbor] = true;
q.push(neighbor);
}
}
}
}
int main() {
int numNodes = 7;
vector<vector<int>> graph(numNodes);
// Add edges to the graph
graph[0].push_back(1);
graph[0].push_back(2);
graph[1].push_back(3);
graph[1].push_back(4);
graph[2].push_back(5);
graph[2].push_back(6);
int startNode = 0;
cout << "DFS traversal: ";
vector<bool> visitedDFS(numNodes, false);
dfs(graph, visitedDFS, startNode);
cout << endl;
cout << "BFS traversal: ";
bfs(graph, startNode);
cout << endl;
return 0;
}