Pagini recente » Cod sursa (job #901060) | Cod sursa (job #1850938) | Cod sursa (job #2336650) | Cod sursa (job #372931) | Cod sursa (job #2796142)
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>
using namespace std;
ifstream in("bfs.in");
ofstream out("bfs.out");
const int maxi=100001;
class Graf
{
private:
int n,m,s;
vector<int> v[maxi];
public:
Graf(bool tip);
void bfs();
};
Graf::Graf(bool tip)
{
int i;
in>>n>>m>>s;
for(i=1; i<=m; i++)
{
int x,y;
in>>x>>y;
v[x].push_back(y);
if(tip==false)//e neorientat
v[y].push_back(x);
}
}
void Graf::bfs()
{
int i;
int dist[n+1];
for(i=1; i<=n; i++)
dist[i]=-1;
dist[s]=0;
queue<int> q;
q.push(s);
while(!q.empty())
{
int nc=q.front();//nod curent
for(i=0; i<v[nc].size(); i++)
{
if(dist[v[nc][i]]==-1)
{
q.push(v[nc][i]);
dist[v[nc][i]]=dist[nc]+1;
}
}
q.pop();
}
for(i=1;i<=n;i++)
out<<dist[i]<<" ";
out.close();
}
int main()
{
Graf g(true);
g.bfs();
return 0;
}