Skip to content

Instantly share code, notes, and snippets.

@prasoon2211
Created July 17, 2015 17:58
Show Gist options
  • Save prasoon2211/ccfa6e6314f9637f9cd8 to your computer and use it in GitHub Desktop.
Save prasoon2211/ccfa6e6314f9637f9cd8 to your computer and use it in GitHub Desktop.
challenges/bfsshortreach
#include <cmath>
#include <cstdio>
#include <vector>
#include <list>
#include <queue>
#include <iostream>
#include <algorithm>
using namespace std;
class Graph {
public:
vector <vector <int>> adj_list;
bool hasEdge(int i, int j) {
for(int index=0; index < adj_list[i].size(); index++) {
if(adj_list[i][index] = j)
return true;
}
return false;
}
void addEdge(int i, int j) {
if(this.hasEdge(i, j))
return;
adj_list[i].push_back(j);
adj_list[j].push_back(i);
}
void removeEdge(int i, int j) {
if(!this.hasEdge(i, j))
return;
for(int index=0; index < adj_list[i].size(); index++) {
if(adj_list[i][index] = j) {
adj_list[i].erase(adj_list[i].begin() + index);
break;
}
}
}
void addNode(int i) {
adj_list[i] = vector<int>;
}
void addNodes(int N) {
for(int i=1; i <= N; i++) {
this.addNode(i);
}
}
~Graph() {
for(int index=0; index < adj_list.size(); index++) {
delete adj_list[index];
}
delete this.adj_list;
}
}
int bfs(Graph g, int start, int end) {
int dist = 0;
int pred[g.adj_list.size()] = {0};
vector <int> visited;
queue <int> q;
q.push(start);
visited.push_back(start);
while(!q.empty) {
int curr = q.front();
q.pop();
// get nbrs of curr
for(int i=0; i< g.adj_list[curr].size(); i++) {
if(i == end) {
// reached our detination
}
if(visited(i))
continue;
q.push(i);
visited.push_back(i);
}
}
}
int cost(Graph g, int i, int j) {
if(!g.hasEdge(i, j))
return -1;
else return 6;
}
int main() {
int cases, edges, nodes, start;
cin >> cases;
while (cases--) {
cin >> nodes >> edges;
Graph g;
g.addNodes(nodes);
while(edges--) {
int i, j;
cin >> i >> j;
g.addEdge(i, j);
}
cin >> start;
for(int index=1; index < g.adj_list.size(); index++) {
if(index == start)
continue;
cout << bfs()
}
delete g;
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment