Advertisement
newb_ie

bfs

Nov 13th, 2021
211
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.66 KB | None | 0 0
  1. #include "bits/stdc++.h"
  2.  
  3. using namespace std;
  4.  
  5. const int maxN = 100;
  6. bool visited[maxN];
  7. int cost[maxN];
  8. vector<int> adj[maxN];
  9.  
  10. void bfs (int source) {
  11. queue<int> q;
  12. q.push(source);
  13. cost[source] = 0;
  14. visited[source] = true;
  15. while (!q.empty()) {
  16. int u = q.front();
  17. q.pop();
  18. for (int v : adj[u]) {
  19. if (!visited[v]) {
  20. cost[v] = cost[u] + 1;
  21. visited[v] = true;
  22. q.push(v);
  23. }
  24. }
  25. }
  26. }
  27.  
  28. int main () {
  29. int n = 5, m = 5;
  30. for (int i = 1; i <= m; ++i) {
  31. int u, v;
  32. cin >> u >> v;
  33. adj[u].push_back(v);
  34. adj[v].push_back(u);
  35. }
  36. bfs(1);
  37. for (int i = 1; i <= n; ++i) cout << cost[i] << ' ';
  38. }
  39.  
  40.  
  41.  
  42.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement