Pagini recente » Cod sursa (job #1554035) | Cod sursa (job #1162137) | Cod sursa (job #213811) | Cod sursa (job #1376456) | Cod sursa (job #1694287)
#include <iostream>
#include <fstream>
#include <vector>
#include<queue>
using namespace std;
int m,n;
vector< vector <int> > graph;
vector<bool> visited;
vector<int> dist;
queue<int> q;
void bfs(int vertex)
{
int element;
if(vertex<0 || vertex>n-1)
return;
q.push(vertex);
visited[vertex]=true;
while(!q.empty())
{
element=q.front();
//cout<<element<<" ";
for(int i=0;i<graph[element].size();i++)
{if(!visited[graph[element][i]])
{q.push( graph[element][i]);
dist[graph[element][i]]=dist[element]+1;
}
visited[graph[element][i]]=true;
}
q.pop();
}
}
int main()
{int nr;
ifstream f("dfs.in");
ofstream g("dfs.out");
f>>n>>m>>nr;
graph.resize(n);
visited.resize(n,false);
dist.resize(n,-1);
int x,y;
for(int i=0;i<m;i++)
{
f>>x>>y;
x--;
y--;
graph[x].push_back(y);
//graph[y].push_back(x);
}
//cout<<nr;
dist[nr-1]=0;
bfs(nr-1);
for(int i=0;i<n;i++)
g<<dist[i]<<" ";
return 0;
}