Pagini recente » Cod sursa (job #287581) | Cod sursa (job #901994) | Cod sursa (job #2259525) | Cod sursa (job #1730099) | Cod sursa (job #3145387)
#include <fstream>
#include <vector>
#include <queue>
using namespace std;
ifstream fin("bfs.in");
ofstream fout("bfs.out");
const int N_MAX = 1e5;
vector<int> adj[N_MAX];
int dist[N_MAX]{};
void bfs(int start){
queue<int> q;
dist[start] = 1;
q.push(start);
while(!q.empty()){
int node = q.front();
for(auto neighbour: adj[node])
if(!dist[neighbour]){
dist[neighbour] = dist[node] + 1;
q.push(neighbour);
}
q.pop();
}
}
int main(){
int nodes, edges, start, a, b;
fin >> nodes >> edges >> start;
--start;
for(int i = 0; i < edges; ++i){
fin >> a >> b;
--a;
--b;
adj[a].push_back(b);
}
bfs(start);
for(int node = 0; node < nodes; ++node)
fout << dist[node] - 1 << ' ';
fout.put('\n');
fin.close();
fout.close();
return 0;
}