Pagini recente » Cod sursa (job #1261653) | Cod sursa (job #1889152) | Cod sursa (job #1851895) | Cod sursa (job #2419612) | Cod sursa (job #668262)
Cod sursa(job #668262)
#include <fstream>
#include <string.h>
#include <vector>
#include <queue>
using namespace std;
#define MAXSIZE 100001
ifstream in("bfs.in");
ofstream out("bfs.out");
int nodes,edges,source;
int dist[MAXSIZE];
queue<int> list;
vector<int> graph[MAXSIZE];
void breadthFirst(int startNode);
int main()
{
in >> nodes >> edges >> source;
int from,to;
for(int i=1;i<=edges;i++)
{
in >> from >> to;
graph[from].push_back(to);
}
in.close();
breadthFirst(source);
for(int i=1;i<=nodes;i++)
if(dist[i] == 0 && i != source)
out << "-1 ";
else
out << dist[i] << " ";
out << "\n";
out.close();
return (0);
}
void breadthFirst(int startNode)
{
int currentNode;
vector<int>::iterator end;
list.push(startNode);
while(!list.empty())
{
currentNode = list.front();
list.pop();
end = graph[currentNode].end();
for(vector<int>::iterator it=graph[currentNode].begin();it!=end;++it)
if(!dist[*it] && source != *it)
{
list.push(*it);
dist[*it] = dist[currentNode] + 1;
}
}
}