Advertisement
iStrzalka

BFS

Apr 21st, 2017
233
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.88 KB | None | 0 0
  1. #include <iostream>
  2. #include <vector>
  3. using namespace std;
  4.  
  5. struct node{
  6.     vector <int> polaczenia;
  7.     int self = 10000000;
  8. };
  9.  
  10. node graph[1000000];
  11.  
  12. void BFS(int START = 1, int value = -1)
  13. {
  14.     graph[START].self = value + 1;
  15.     int ile;
  16.     for(int i = 0; i < graph[START].polaczenia.size(); i++){
  17.         ile = graph[START].polaczenia[i];
  18.         if(graph[START].self + 1 < graph[ile].self){
  19.             BFS(ile,graph[START].self);
  20.         }
  21.     }
  22. }
  23.  
  24. int main()
  25. {
  26.     int n,m,from, to, cost;
  27.     cin >> n >> m;
  28.  
  29.     for(int i = 0;i < m; i++)
  30.     {
  31.         cin >> from >> to;
  32.         graph[from].polaczenia.push_back(to);
  33.         graph[to].polaczenia.push_back(from);
  34.     }
  35.  
  36.     BFS();
  37.  
  38.     for(int i = 1; i <= n; i++)
  39.         if(graph[i].self != 10000000)
  40.             cout << graph[i].self << endl;
  41.         else
  42.             cout << -1 << endl;
  43. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement