Cod sursa(job #2958280)

Utilizator CondoracheAlexandruCondorache Alexandru CondoracheAlexandru Data 25 decembrie 2022 17:02:39
Problema BFS - Parcurgere in latime Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.71 kb
#include <bits/stdc++.h>
 
using namespace std;
 
vector<int>adiac[100005];
bool viz[100005];
int dist[100005];
int n,m,s;
 
 
int main() {
	ifstream cin("bfs.in");
	ofstream cout("bfs.out");
	cin >> n >> m >> s;
	for (int i=1; i<=m; i++) {
		int x,y;
		cin >> x >> y;
		adiac[x].push_back(y);
	}
	for (int i=1; i<=n; i++) {
		if (i==s)dist[i]=0;
		else {
			dist[i]=-1;
		}
	}
	queue<int>q;
	q.push(s);
	viz[s]=1;
	while (!q.empty()) {
		int nod=q.front();
		for (auto it:adiac[nod]) {
			if (viz[it]==1)continue;
			else {
				q.push(it);
				dist[it]=dist[nod]+1;
				viz[it]=1;
			}
		}
		q.pop();
	}
	
	
	
	for (int i=1; i<=n; i++) {
	
		 cout << dist[i] << " ";
	}	
}