Graph can be represented using adjacency matrix.
Adjacency matrix is a square matrix (m[N][N]) used to represent a graph where N is the number of vertices. The presence of edge between i and j is denoted by m[i][j] = 1 and absence by m[i][j] = 0
#include <iostream>
#include <queue>
#include <vector>
using namespace std;
#define N 4
//Adjacency matrix of graph
int matrix[4][4] =
{{0, 1, 1, 0},
{1, 0, 0, 1},
{1, 0, 0, 0},
{0, 1, 0, 0}};
class Graph {
public:
vector<int> adj_[N];
void addEdge(int u, int v) {
// In case of undirected graph, to and fro traversal is allowed
adj_[u].push_back(v);
adj_[v].push_back(u);
}
void bfs(int src) {
vector<bool> visited(N, false);
vector<int> distance(N, 0);
queue<int> q;
q.push(src);
visited[src] = true;
distance[src] = 0;
vector<int> path;
while (!q.empty()) {
int u = q.front();
q.pop();
path.push_back(u);
for (auto v : adj_[u]) {
if (!visited[v]) {
q.push(v);
visited[v] = true;
distance[v] = distance[u] + 1;
}
}
}
cout << "Breadth First Traversal: starting from vertex: " << src << endl;
for (auto d : path) cout << d << " ";
cout << endl;
cout << "Distance of nodes from : " << src << endl;
for (int i = 0; i < distance.size(); i++)
cout << "to node " << i << " -> " << distance[i] << endl;
}
};
int main() {
Graph g;
for (size_t i = 0; i < 4; i++) {
for (size_t j = 0; j < 4; j++) {
if (matrix[i][j] && i > j) g.addEdge(i, j);
}
}
g.bfs(0);
return 0;
}Breadth First Traversal: starting from vertex: 0 0 1 2 3 Distance of nodes from : 0 to node 0 -> 0 to node 1 -> 1 to node 2 -> 1 to node 3 -> 2
References