BFS and DFS
BFS and DFS
#include <iostream>
#include <vector>
#include <queue>
visited[start] = true;
q.push(start);
while (!q.empty()) {
q.pop();
if (!visited[neighbor]) {
visited[neighbor] = true;
q.push(neighbor);
int main() {
vector<vector<int>> adjList(vertices);
int u, v;
adjList[u].push_back(v);
int start;
bfs(start, adjList);
return 0;
BFS Algorithm
Input:
Output:
o Create a visited list or array to track visited nodes. Initialize all entries to false.
4. Repeat:
o Continue until all reachable nodes from sss have been visited.
5. End:
o The traversal is complete. If desired, repeat the process for other components of the graph (if
disconnected).
DFS::::::
#include <iostream>
#include <vector>
#include <stack>
stack<int> s;
s.push(start);
visited[start] = true;
while (!s.empty()) {
s.pop();
if (!visited[neighbor]) {
visited[neighbor] = true;
s.push(neighbor);
int main() {
vector<vector<int>> adjList(vertices);
int u, v;
adjList[u].push_back(v);
int start;
dfs(start, adjList);
return 0;
}
DFS Algorithm
1. Initialize:
3. Traverse Neighbors:
o Continue the process until all nodes in the stack or call stack have been exhausted.