Pagini recente » Cod sursa (job #2789677) | Cod sursa (job #2497982) | Cod sursa (job #2217959) | Cod sursa (job #549190) | Cod sursa (job #2529593)
#include<fstream>
#include<iostream>
#include<list>
#include<cstring>
#include<vector>
using namespace std;
ifstream f("bfs.in");
ofstream o("bfs.out");
class Graph{
list<int>*Adj;
public:Graph(int n){
Adj=new list<int>[n];
}
public:int addEdge(int x, int y){
Adj[x].push_back(y);
return 0;
}
public:int bfs(int s, int n){
list<int>::iterator i;
vector<int>cost(n, -1);
list<int>q;
q.push_back(s);
cost[s]=0;
while(!q.empty()){
s=q.front();
q.pop_front();
for(i=Adj[s].begin(); i!=Adj[s].end(); i++){
if(cost[(*i)]==-1){
q.push_back((*i));
cost[(*i)]=cost[s]+1;
}
}
}
for(int i=1;i<n;i++){
o<<cost[i]<<" ";
}
return 0;
}
};
int main(){
int n, m, s, x, y;
f>>n>>m>>s;
Graph g(n+1);
for(int i=0;i<m;i++){
f>>x>>y;
g.addEdge(x, y);
}
g.bfs(s, n+1);
}