Advertisement
fuadnafiz98

Untitled

May 13th, 2019
114
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.86 KB | None | 0 0
  1. #include <iostream>
  2. #include <vector>
  3. #include <queue>
  4.  
  5. using namespace std;
  6.  
  7. vector <int> adj[100];
  8. int visited[100];
  9. int dist[100];
  10.  
  11. void bfs(int node)
  12. {
  13.   visited[node] = true;
  14.   dist[node] = 0;
  15.   queue <int> q;
  16.   q.push(node);
  17.   while(!q.empty())
  18.   {
  19.     int u = q.front();
  20.     q.pop();
  21.     for(int i = 0; i < adj[u].size(); i++)
  22.     {
  23.         int v = adj[u][i];
  24.         if(visited[v] == false)
  25.         {
  26.             dist[v] = dist[u] + 1;
  27.             visited[v] = true;
  28.             q.push(v);
  29.         }
  30.     }
  31.   }
  32. }
  33.  
  34. int main()
  35. {
  36.     int node, edge;
  37.     cin >> node >> edge;
  38.     for(int i = 0; i < edge; i++)
  39.     {
  40.         int u, v;
  41.         cin >> u >> v;
  42.         adj[u].push_back(v);
  43.     }
  44.     bfs(1);
  45.     for(int i = 1; i <= node; i++)
  46.       cout << "Node -> " << i << " distance of this node -> " << dist[i] << '\n';
  47. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement