Pagini recente » Cod sursa (job #2593015) | Cod sursa (job #1622301) | Cod sursa (job #1644953) | Cod sursa (job #1071648) | Cod sursa (job #1618525)
#include <iostream>
#include <cstdlib>
#include <vector>
#include <queue>
#include <fstream>
using namespace std;
int m, n;
vector <vector <int> > graph;
vector <int> visited;
ifstream f("bfs.in");
ofstream h("bfs.out");
void bfs(int vertex,int n)
{
if (vertex<0 || vertex>n - 1) return;
queue <int> q;
int element, i;
bool found;
q.push(vertex);
for(i=0;i<n;i++) visited[i]=-1;
visited[vertex] = 0;
while (!q.empty())
{
element = q.front();
for (i = 0; i < graph[element].size(); i++)
if (visited[graph[element][i]]==-1)
{
q.push(graph[element][i]);
visited[graph[element][i]] = visited[element]+1;
}
q.pop();
}
for (i = 0; i < visited.size(); i++) h << visited[i] << " ";
h << "\n";
}
int main()
{
int x, y, i,a,nod;
f >> n >> m >> nod;
nod--;
graph.resize(n);
visited.resize(n, false);
for (i = 0; i<m; i++)
{
f >> x >> y;
x--; y--;
graph[x].push_back(y);
}
bfs(nod,n);
f.close();
h.close();
return 0;
}