Pagini recente » Cod sursa (job #2313051) | Cod sursa (job #1052683) | Statistici Craciun George (GeorgeCraciun) | Cod sursa (job #2549162) | Cod sursa (job #1636061)
#include <iostream>
#include <vector>
#include <queue>
#include <fstream>
using namespace std;
ifstream f("bfs.in");
ofstream g("bfs.out");
int n,m;
vector<vector<int> >graph;
vector<int>visited;
void bfs(int vertex)
{if(vertex<0||vertex>n-1)
return;
queue<int> q;
int element,i;
q.push(vertex);
visited[vertex]++;
while(!q.empty())
{element=q.front();
for(i=0;i<graph[element].size();i++)
if(visited[graph[element][i]]==-1)
{q.push(graph[element][i]);
visited[graph[element][i]]=visited[element]+1;
}
q.pop();
}
}
int main()
{int s;
f>>n>>m>>s;
graph.resize(n*m);
visited.resize(n,-1);
int x,y,i;
for(i=0;i<m;i++)
{
f>>x>>y;
x--;
y--;
graph[x].push_back(y);
}
int j,k;
for(j=0;j<n;j++)
{cout<<j+1<<": ";
for(k=0;k<graph[j].size();k++)
if(graph[j][k]>=0&&graph[j][k]<n)
cout<<graph[j][k]+1<<" ";
cout<<endl;
}
bfs(s-1);
for(i=0;i<visited.size();i++)//am putea salva size in variabila sa nu o calculeze mereu
g<<visited[i]<<" ";
return 0;
}