Pagini recente » Monitorul de evaluare | Monitorul de evaluare | Borderou de evaluare (job #2506647) | Cod sursa (job #3336247) | Cod sursa (job #3337046)
///BFS
#include <iostream>
#include <queue>
#include <vector>
#include <fstream>
#include <algorithm>
using namespace std;
ifstream f("bfs.in");
ofstream g("bfs.out");
int main()
{
int N, M, start;
f >> N >> M >> start;
int viz[N+1]={0}; //initialize all positions with 0
vector<int> adj[N+1];
int levels[N+1];
for(int i = 1;i<=N;i++)
levels[i]=-1; //initialize all positions with -1
for(int i = 0; i<M;i++)
{
int u,v;
f>>u>>v;
adj[u].push_back(v);
//adj[v].push_back(u); //if the graph is undirected
}
//for(int i =1; i<=N;i++)
//sort(adj[i].begin(), adj[i].end());
queue<int> Q;
Q.push(start);
viz[start]=1;
levels[start] = 0;
while(!Q.empty())
{
int nod = Q.front();
Q.pop();
//g << nod << " ";
for(int vecin : adj[nod])
{
if(!viz[vecin])
{
levels[vecin] = levels[nod] + 1;
Q.push(vecin);
viz[vecin] = 1;
}
}
}
///if the graph is not connected and you want to go through all the nodes this should work
/*
for(int i = 1 ; i<=N; i++)
{
if(viz[i]==0)
{
Q.push(i);
viz[i]=1;
while(!Q.empty())
{
int nod = Q.front();
Q.pop();
g << nod << " ";
for(int vecin : adj[nod])
{
if(!viz[vecin])
{
Q.push(vecin);
viz[vecin] = 1;
}
}
}
}
}
*/
for(int i = 1; i<=N;i++)
g << levels[i]<< " ";
f.close();
g.close();
return 0;
}