Skip to content

Instantly share code, notes, and snippets.

@chermehdi
Created June 4, 2020 12:13
Show Gist options
  • Save chermehdi/519f57f8ff8026ea83c9ea817260f00f to your computer and use it in GitHub Desktop.
Save chermehdi/519f57f8ff8026ea83c9ea817260f00f to your computer and use it in GitHub Desktop.
A simple graph traversal example: using bfs
#include <iostream>
#include <vector>
#include <queue>
using namespace std;
// Sample input
// 4 4
// 0 1
// 0 2
// 1 3
// 2 3
// 0
// Graph datastructure -> Adjecency list
vector<vector<int>> g;
int main() {
freopen("graph.in", "r", stdin);
int n, m; // number of vertices and edges
cin >> n >> m;
g.resize(n);
for(int i = 0; i < m; ++i) {
int u, v; cin >> u >> v;
// suppose that the graph is undirected
g[u].push_back(v);
// This should be omited if the graph is directed.
g[v].push_back(u);
}
// node from where to start the discovery
int start; cin >> start;
queue<int> q;
vector<bool> seen(n, false);
q.push(start);
seen[start] = true;
while(!q.empty()) {
int u = q.front(); q.pop();
cout << "visiting " << u + 1<< endl;
for(int v: g[u]) {
if(seen[v]) {
continue;
}
seen[v] = true;
q.push(v);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment