Cod sursa(job #3278501)

Utilizator RaaaareeesLeah Rares Raaaareees Data 19 februarie 2025 22:40:10
Problema BFS - Parcurgere in latime Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.05 kb
#include <iostream>
#include <fstream>
using namespace std;

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

int matrice[100001][100001] = { 0 };
int nvizitat[100001] = { 0 };
int coada[100001] = { 0 };
int drum[100001] = {  };

void citire(int m, int n)
{
	int i = 0;
	int j = 0;

	for (int x = 0; x < m; x++)
	{
		fin >> i >> j;
		matrice[i][j] = 1;
	}
	for (int x = 1; x <= n; x++)
	{
		drum[x] = -1;
	}
}

int l = 0;

void bfs(int k, int n)
{
	nvizitat[k] = 1;

	coada[l] = k;
	l++;

	drum[k] = 0;

	int index = 0;

	while (index < l)
	{
		int ncurent = coada[index];
		for (int x = 1; x <= n; x++)
		{
			if (matrice[ncurent][x] == 1)
			{
				if (nvizitat[x] == 0)
				{
					coada[l] = x;
					l++;
					nvizitat[x] = 1;
					drum[x] = drum[ncurent] + 1;
				}
			}
		}
		index++;
	}
}

void afisare(int n)
{
	for (int x = 1; x <= n; x++)
	{
		fout << drum[x] << " ";
	}
}

int main()
{
	int n = 0;
	int m = 0;
	int x = 0;

	fin >> n >> m >> x;

	citire(m,n);

	bfs(x, n);

	afisare(n);
}