Cod sursa(job #1747924)

Utilizator Tester100Tester Tester100 Data 25 august 2016 19:45:40
Problema BFS - Parcurgere in latime Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 0.79 kb
#include<bits/stdc++.h>
#define in f
#define out cout 
using namespace std;

ifstream f("bfs.in");
ofstream g("bfs.out");

const int MAXN = 100001;

vector<int> G[MAXN];
int n, m, s;
int depth[MAXN];

void read() {
  in >> n;
  in >> m;
  in >> s;

  int x, y;

  for(int i = 1; i <= m; i++) {
    in >> x;
    in >> y;
    G[x].push_back(y);
  }
  
}

void bfs(int node) {
  queue<int> q;
  q.push(node);
  depth[node] = 0;

  while(q.empty() == false) {
    node = q.front();
    q.pop();

    for(auto vertex : G[node]) {
      if(depth[vertex] == -1) {
        q.push(vertex);
        depth[vertex] = depth[node] + 1;
      }
    }
  }
}

int main() {
  read();
  for(int i = 0; i <= n; i++) {
    depth[i] = -1;
  }

  bfs(s);

  for(int i = 1; i <= n; i++) {
    out << depth[i] << " ";
  }

  return 0;
}