Pagini recente » Cod sursa (job #82464) | Cod sursa (job #2878064) | Cod sursa (job #268985) | Cod sursa (job #2490049) | Cod sursa (job #535538)
Cod sursa(job #535538)
// http://infoarena.ro/problema/bfs
#include <fstream>
#include <vector>
#include <list>
#include <queue>
using namespace std;
int nodes,edges,startNode;
vector< list<int> > graph;
vector<int> visited;
queue<int> myQueue;
void read();
void breadthFirst(int startNode);
void write();
int main() {
read();
breadthFirst(startNode);
write();
return (0);
}
void read() {
ifstream in("bfs.in");
int from,to;
in >> nodes >> edges >> startNode;
graph.resize(nodes+1);
visited.resize(nodes+1);
for(int i=1;i<=edges;i++) {
in >> from >> to;
if(from != to)
graph.at(from).push_back(to);
}
in.close();
}
void breadthFirst(int startNode) {
int node;
myQueue.push(startNode);
visited.at(startNode) = 1;
while(!myQueue.empty())
{
node = myQueue.front();
myQueue.pop();
for(list<int>::iterator it=graph.at(node).begin();it!=graph.at(node).end();it++)
if(!visited.at(*it))
{
myQueue.push(*it);
visited.at(*it) = visited.at(node) + 1;
}
}
}
void write() {
ofstream out("bfs.out");
for(int i=1;i<=nodes;i++)
out << visited.at(i) - 1 << " ";
out.close();
}