Algorithm BFS DFS
Algorithm BFS DFS
BFS
#include <iostream>
#include <list>
#include <queue>
class Graph {
int vertices; // Number of vertices
list<int> *adjList; // Pointer to an array containing adjacency lists
public:
// Constructor
Graph(int v) {
vertices = v;
adjList = new list<int>[v];
}
while (!q.empty()) {
// Dequeue a vertex from the queue and print it
start = q.front();
cout << start << " ";
q.pop();
int main() {
Graph g(4);
g.addEdge(0, 1);
g.addEdge(0, 2);
g.addEdge(1, 2);
g.addEdge(2, 0);
g.addEdge(2, 3);
g.addEdge(3, 3);
cout << "Breadth First Traversal starting from vertex 2:" << endl;
g.bfs(2);
return 0;
}
2. DFS
#include <iostream>
#include <list>
class Graph {
int vertices; // Number of vertices
list<int> *adjList; // Pointer to an array containing adjacency lists
public:
// Constructor
Graph(int v) {
vertices = v;
adjList = new list<int>[v];
}
int main() {
Graph g(4);
g.addEdge(0, 1);
g.addEdge(0, 2);
g.addEdge(1, 2);
g.addEdge(2, 0);
g.addEdge(2, 3);
g.addEdge(3, 3);
cout << "Depth First Traversal starting from vertex 2:" << endl;
g.dfs(2);
return 0;
}
Given an unweighted graph and a source node, find the shortest path from the source node to
all other nodes in the graph.
Input:
Graph: 0 -> 1 -> 2
| |
v v
3 -> 4
Source: 0
Output:
Distance from 0 to 0: 0
Distance from 0 to 1: 1
Distance from 0 to 2: 2
Distance from 0 to 3: 1
Distance from 0 to 4: 2
Input: