Pagini recente » Cod sursa (job #1881369) | Cod sursa (job #804151) | Cod sursa (job #369009) | Cod sursa (job #1782753) | Cod sursa (job #1686947)
#include <fstream>
std::ifstream fin("bfs.in");
std::ofstream fout("bfs.out");
#include <vector>
#include <queue>
class Graph {
private:
std::vector<std::vector<int> > graphMap;
public:
Graph();
Graph(int);
~Graph();
void addNode();
void pushVertex(int, int);
std::vector<int> getDistanceMap(int);
};
int main()
{
int N, M, S;
fin >> N >> M >> S;
Graph *graph = new Graph(N);
for (int i = 0; i < M; i++) {
int a, b;
fin >> a >> b;
graph->pushVertex(a - 1, b - 1);
//graph->pushVertex(b - 1, a - 1);
}
std::vector<int> rs = graph->getDistanceMap(S - 1);
return 0;
}
Graph::Graph() {}
Graph::Graph(int nodes) {
for (int i = 0; i < nodes; i++) {
this->addNode();
}
}
Graph::~Graph() {}
void Graph::addNode() {
this->graphMap.push_back(std::vector<int>());
}
void Graph::pushVertex(int fromNode, int toNode) {
this->graphMap[fromNode].push_back(toNode);
}
std::vector<int> Graph::getDistanceMap(int fromNode) {
std::vector<int> temp;
for (int i = 0; i < this->graphMap.size(); i++) {
temp.push_back(-1);
}
temp[fromNode] = 0;
std::queue<int> queue;
queue.push(fromNode);
while (!queue.empty()) {
int front = queue.front();
queue.pop();
for (std::vector<int>::iterator it = this->graphMap[front].begin(); it != graphMap[front].end(); it++) {
if (temp[*it] == -1) {
temp[*it] = temp[front] + 1;
queue.push(*it);
}
else if (temp[front] + 1 < temp[*it]) {
queue.push(*it);
temp[*it] = temp[front] + 1;
}
}
}
return temp;
}