Pagini recente » Cod sursa (job #2378604) | Cod sursa (job #1053765) | Cod sursa (job #2367416) | Cod sursa (job #2161065) | Cod sursa (job #3164942)
#include <iostream>
#include <fstream>
#include <list>
#include <vector>
#include <queue>
using namespace std;
ifstream fin("bfs.in");
ofstream fout("bfs.out");
int n, m, s;
int v[100000][100000];
void memorareMatrice(bool orientat)
{
fin >> n >> m;
int x, y;
for (int i = 1; i <= m; i++)
{
fin >> x >> y;
if (orientat) v[x][y] = 1;
else
{
v[x][y] = 1;
v[y][x] = 1;
}
}
}
void afisareMatrice(int n)
{
for (int i = 1; i <= n; i++)
{
for (int j = 1; j <= n; j++)
cout << v[i][j] << " ";
cout << '\n';
}
}
vector<list<int>> liste(100000);
void memorareListe(bool orientat)
{
fin >> n >> m >> s;
int x, y;
for (int i = 1; i <= m; i++)
{
fin >> x >> y;
liste[x].push_back(y);
if (!orientat) liste[y].push_back(x);
}
}
void afisareListe(int n)
{
for (int i = 1; i <= n; i++)
{
cout << "Nodul " << i << ": ";
for (auto vecin : liste[i])
cout << vecin << " ";
cout << '\n';
}
}
void BFS(int start)
{
int vis[100000] = {0};
int d[100000];
for (int i = 1; i <= n; i++)
d[i] = -1;
queue<int> q;
q.push(start);
d[start] = 0;
vis[start] = 1;
int x;
while (!q.empty())
{
x = q.front();
q.pop();
for (auto next:liste[x])
{
if (!vis[next])
{
q.push(next);
vis[next] = 1;
d[next] = d[x] + 1;
}
}
}
for (int i = 1; i <= n; i++)
fout << d[i] << " ";
}
int main()
{
bool orientat = true;
//memorareMatrice(orientat);
//afisareMatrice(n);
memorareListe(orientat);
//afisareListe(n);
BFS(s);
return 0;
}