Pagini recente » Cod sursa (job #1326482) | Cod sursa (job #2846429) | Cod sursa (job #1722344) | Cod sursa (job #1035488) | Cod sursa (job #3208246)
#include <fstream>
#include <queue>
#include <iostream>
using namespace std;
ifstream in("bfs.in");
ofstream out("bfs.out");
const int NMAX= 100001;
bool a[NMAX][NMAX];
int N,M,S;
int dis[NMAX];
void readIn(){
int x,y;
in >> N >> M >> S;
for(int i = 0; i < M; i++){
in >> x >> y;
a[x][y]=true;
}
}
void bfs(){
queue<int> q;
q.push(S);
dis[S]=1;
while(!q.empty()){
int current_node = q.front();
//cout << current_node << " : ";
q.pop();
for (int neighbor = 1; neighbor <= N; neighbor++) {
if (a[current_node][neighbor] && !dis[neighbor]) {
q.push(neighbor);
//cout << neighbor << " ";
dis[neighbor] = dis[current_node] + 1;
}
} //cout <<endl;
}
}
int main(){
readIn();
bfs();
for (int i = 1; i <= N; i ++){
out << dis[i]-1 << " ";
}
}