Cod sursa(job #3155970)

Utilizator boteBotezatu Cosmin bote Data 10 octombrie 2023 12:54:05
Problema BFS - Parcurgere in latime Scor 50
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.93 kb
/*#include <iostream>
#include <fstream>
#include <vector>
using namespace std;

ifstream fin("graf.in");

int a[1005][1005];
int n, m;
vector<int> G[1005];

void readListe()
{
	fin >> n >> m;
	for (int i = 1; i <= m; i++)
	{
		int x, y;
		fin >> x >> y;
		G[x].push_back(y);
		G[y].push_back(x);
	}
}

void showNe()
{
	for(int i=1;i<=n;i++)
		for ( auto x:G[i])
			cout << x << " ";
}

void readNeorientat()
{
	fin >> n >> m;
	for (int i = 1; i <= m; i++)
	{
		int x, y;
		fin >> x >> y;
		a[x][y] = a[y][x] = 1;
	}
}

void readOrientat()
{
	fin >> n >> m;
	for (int i = 1; i <= m; i++)
	{
		int x, y;
		fin >> x >> y;
		a[x][y] = 1;
	}
}

void show()
{
	for (int i = 1; i <= n; i++)
	{
		for(int j=1; j<=n; j++)
			cout << a[i][j] << " ";
		cout << endl;
	}
}

int main()
{
	readListe();
	showNe();
	return 0;
}
*/




#include <iostream>
#include <fstream>
using namespace std;

ifstream fin("bfs.in");
ofstream fout("bfs.out");

#define N 10005

int a[N][N];
int n, m, source;
int viz[N];
void read()
{
	fin >> n >> m >> source;
	for (int i = 1; i <= m; i++)
	{
		int x, y;
		fin >> x >> y;
		a[x][y] = 1;
	}
}

void bfs(int x)
{
	int c[N], p, u;
	p = u = 1;
	c[1] = x;
	viz[x] = 1;
	while (p <= u)
	{
		int nod = c[p++];
		fout << nod << " ";
		for (int i = 1; i <= n; i++)
			if (a[nod][i] && !viz[i])
			{
				c[++u] = i;
				viz[i] = 1;
			}
	}
}
//calculate the minimum distance from source to all other nodes
void bfs2(int x)
{
	int c[N], p, u;
	p = u = 1;
	c[1] = x;
	viz[x] = 1;
	int d[N];
	for (int i = 1; i <= n; i++)
		d[i] = -1;
	d[x] = 0;
	while (p <= u)
	{
		int nod = c[p++];
		for (int i = 1; i <= n; i++)
			if (a[nod][i] && !viz[i])
			{
				c[++u] = i;
				viz[i] = 1;
				d[i] = d[nod] + 1;
			}
	}
	for (int i = 1; i <= n; i++)
		fout << d[i] << " ";
}

int main()
{
	read();
	bfs2(source);
	return 0;
}