Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
71 changes: 71 additions & 0 deletions BFS_DFS_ALGO/BFS.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
#include <iostream>
#include <vector>
#include <queue>
using namespace std;

void bfs(int start, vector<vector<int>>& adj, int n) {
vector<bool> visited(n, false);
queue<int> q;

visited[start] = true;
q.push(start);

cout << "BFS Traversal: ";

while (!q.empty()) {
int node = q.front();
q.pop();
cout << node << " ";

for (int neighbour : adj[node]) {
if (!visited[neighbour]) {
visited[neighbour] = true;
q.push(neighbour);
}
}
}
}

int main() {
int n, edges;

cout << "Enter number of nodes: ";
cin >> n;

cout << "Enter number of edges: ";
cin >> edges;

vector<vector<int>> adj(n);

cout << "Enter edges (u v):\n";
for (int i = 0; i < edges; i++) {
int u, v;
cin >> u >> v;

adj[u].push_back(v);
adj[v].push_back(u);
}

int start;
cout << "Enter starting node for BFS: ";
cin >> start;

bfs(start, adj, n);

return 0;
}

//Test Cases-
//--------INPUT---------------------------
// Enter number of nodes: 5
// Enter number of edges: 4
// Enter edges (u v):
// 0 1
// 0 2
// 1 3
// 2 4
// Enter starting node for BFS: 0

//-----OUTPUT-------------------------------
// BFS Traversal: 0 1 2 3 4

Binary file added BFS_DFS_ALGO/BFS.exe
Binary file not shown.
59 changes: 59 additions & 0 deletions BFS_DFS_ALGO/DFS.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
#include <iostream>
#include <vector>
using namespace std;

void dfs(int node, vector<vector<int>>& adj, vector<bool>& visited) {
visited[node] = true;
cout << node << " ";

for (int neighbour : adj[node]) {
if (!visited[neighbour]) {
dfs(neighbour, adj, visited);
}
}
}

int main() {
int n, edges;

cout << "Enter number of nodes: ";
cin >> n;

cout << "Enter number of edges: ";
cin >> edges;

vector<vector<int>> adj(n);
vector<bool> visited(n, false);

cout << "Enter edges (u v):\n";
for (int i = 0; i < edges; i++) {
int u, v;
cin >> u >> v;

adj[u].push_back(v);
adj[v].push_back(u); // if Undirected graph else remove this line
}

int start;
cout << "Enter starting node for DFS: ";
cin >> start;

cout << "DFS Traversal: ";
dfs(start, adj, visited);

return 0;
}

//TEST_CASES-
//-----INPUT---------------------
// Enter number of nodes: 5
// Enter number of edges: 4
// Enter edges (u v):
// 0 1
// 0 2
// 1 3
// 2 4
// Enter starting node for DFS: 0

//-----------OUTPUT--------------
// DFS Traversal: 0 1 3 2 4