Advertisement
Guest User

Untitled

a guest
Oct 24th, 2017
71
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.21 KB | None | 0 0
  1. #include <iostream>
  2. #include <queue>
  3. #include <vector>
  4. #define MAX 100000
  5. using namespace std;
  6. int dist[MAX];
  7. int visit[MAX];
  8. vector <int> vv[MAX];
  9.  
  10. void bfs(int src)
  11. {
  12.     int temp, node;
  13.     queue<int>q;
  14.     q.push(src);
  15.     while(!q.empty())
  16.     {
  17.         temp = q.front(); q.pop();
  18.         for(int i=0;i<vv[temp].size();i++)
  19.         {
  20.             int node = vv[temp][i];
  21.             if(visit[node] == 0)
  22.             {
  23.                 visit[node]=1;
  24.                 dist[node] = dist[temp] + 1;
  25.                 q.push(node);
  26.             }
  27.         }
  28.     }
  29. }
  30. int main()
  31. {
  32.     int n, e, src, target;
  33.     cout << "Enter nodes <space> edges" << endl;
  34.     cin >> n >> e;
  35.     for(int i=1;i<=e;i++)
  36.     {
  37.         //cout << "Enter which nodes " << i << " is connecting to or are connecting to it" << endl;
  38.         int u, v;
  39.         cin >> u >> v;
  40.         vv[u].push_back(v);
  41.         vv[v].push_back(u);
  42.     }
  43.     cout << "Enter source <space> target" << endl;
  44.     cin >> src >> target;
  45.     bfs(src);
  46.     cout << dist[target];
  47. }
  48. /*
  49. 10 13
  50. 1 2
  51. 1 3
  52. 1 4
  53. 2 6
  54. 3 8
  55. 3 7
  56. 4 7
  57. 6 10
  58. 9 10
  59. 9 7
  60. 8 7
  61. 8 5
  62. 5 10
  63.  
  64. 10 14
  65. 1 2
  66. 1 3
  67. 1 4
  68. 2 6
  69. 3 8
  70. 3 7
  71. 4 7
  72. 4 10
  73. 6 10
  74. 9 10
  75. 9 7
  76. 8 7
  77. 8 5
  78. 5 10
  79.  
  80. */
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement