Pagini recente » Cod sursa (job #1573796) | Cod sursa (job #1719693) | Cod sursa (job #280210) | Cod sursa (job #484817) | Cod sursa (job #3253841)
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>
using namespace std;
void bfs(int s, vector<vector<int>> graph)
{
vector<int> dist(graph.size() + 1, -1);
vector<int> visited(graph.size() + 1, 0);
queue<int> q;
q.push(s);
dist[s] = 0;
visited[s] = 1;
while(!q.empty())
{
int node = q.front();
q.pop();
for(int neigh: graph[node]) {
if(visited[neigh] == 0) {
q.push(neigh);
dist[neigh] = dist[node] + 1;
visited[neigh] = 1;
}
}
}
for(int i = 1; i < dist.size() - 1; i++) {
std::cout << dist[i] << ' ';
}
}
int main()
{
ifstream fin("bfs.in");
ofstream fout("bfs.out");
int n, m, s;
fin >> n >> m >> s;
vector<vector<int>> graph(n + 1);
for(int e = 0; e < m; e++)
{
int x, y;
fin >> x >> y;
graph[x].push_back(y);
}
bfs(s, graph);
return 0;
}