Cod sursa(job #2756079)

Utilizator NeoxDragos Stefan Neox Data 29 mai 2021 16:02:49
Problema BFS - Parcurgere in latime Scor 50
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.81 kb
#include <fstream>
#include <vector>
#include <queue>
using namespace std;

int bfs(int n, vector<int> adj[], int st, int end) {
	bool vis[n]{};
	queue<pair<int, int>> Q;
	Q.push({st, 0});
	vis[st] = 1;
	while(!Q.empty()) {
		int currNode = Q.front().first, currDist = Q.front().second;
		Q.pop();
		if(currNode == end) {
			return currDist;
		}
		for(int nxt : adj[currNode]) {
			if(!vis[nxt]) {
				Q.push({nxt, currDist + 1});
				vis[nxt] = 1;
			}
		}
	}
	return -1;
}
int main() {
	ifstream fin("bfs.in");
	ofstream fout("bfs.out");
	int n, m, s;
	fin >> n >> m >> s;
	vector<int> adj[n];
	while(m--) {
		int x, y;
		fin >> x >> y;
		adj[x - 1].push_back(y - 1);
	}
	for(int i = 0; i < n; i++) {
		fout << bfs(n, adj, s - 1, i) << ' ';
	}
	fin.close();
	fout.close();
	return 0;
}