Pagini recente » Cod sursa (job #2225128) | Cod sursa (job #2556178) | Cod sursa (job #1942836) | Cod sursa (job #2449712) | Cod sursa (job #1337310)
#include <fstream>
#include <vector>
#include <queue>
using namespace std;
void bfs(vector<int> adjList[], int cost[], int source);
int main()
{
int N, M, S, x, y, i;
ifstream f("bfs.in");
f >> N >> M >> S;
vector<int> adjList[N + 1];
int cost[N + 1];
for (i = 1; i <= N; i++)
cost[i] = -1;
for (i = 1; i <= M; i++)
{
f >> x >> y;
adjList[x].push_back(y);
}
f.close();
bfs(adjList, cost, S);
ofstream g("bfs.out");
for (i = 1; i <= N; i++)
g << cost[i] << " ";
g.close();
return 0;
}
void bfs(vector<int> adjList[], int cost[], int source)
{
queue<int> q;
q.push(source);
cost[source] = 0;
int x;
while(!q.empty())
{
x = q.front();
q.pop();
for (auto i = adjList[x].begin(); i != adjList[x].end(); i++)
if (cost[*i] == -1)
{
q.push(*i);
cost[*i] = cost[x] + 1;
}
}
}