Advertisement
wintest

bfs

Jan 9th, 2019
283
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.09 KB | None | 0 0
  1. #include<iostream>
  2. #include<algorithm>
  3. #include<queue>
  4. #include<vector>
  5. #include<map>
  6. using namespace std;
  7.  
  8.  
  9. map<int, bool> isFree;
  10. vector<vector<int>> adjMatrix;
  11.  
  12. void BFS(int start) {
  13.     queue<int> que;
  14.  
  15.     isFree[start] = false;
  16.     que.push(start);
  17.  
  18.    
  19.         for (size_t i = 0; i < adjMatrix.size(); i++)
  20.         {
  21.             for (size_t j = 0; j < adjMatrix[i].size(); j++)
  22.             {
  23.  
  24.                 if (isFree[adjMatrix[i][j]]) {
  25.                
  26.                     que.push(adjMatrix[i][j]);
  27.                     isFree[adjMatrix[i][j]] = false;
  28.  
  29.                 }
  30.  
  31.             }
  32.  
  33.         }
  34.  
  35.         while (!que.empty()) {
  36.        
  37.             start = que.front();
  38.             cout << start+1 << " ";
  39.             que.pop();
  40.        
  41.         }
  42.  
  43.  
  44.  
  45. }
  46. int main() {
  47.  
  48.     int N, V;
  49.     cin >> N >> V;
  50.  
  51.    
  52.     for (size_t i = 0; i < N; i++)
  53.     {
  54.         isFree.insert(make_pair(i,true));
  55.     }
  56.     adjMatrix.resize(N);
  57.  
  58.     int a, b;
  59.     for (size_t i = 0; i < V; i++)
  60.     {
  61.         cin >> a >> b;
  62.         adjMatrix[a-1].push_back(b-1);
  63.         adjMatrix[b-1].push_back(a-1);
  64.     }
  65.     for (size_t i = 0; i < adjMatrix.size(); i++)
  66.     {
  67.         for (size_t j = 0; j < adjMatrix[i].size(); j++)
  68.         {
  69.             cout << adjMatrix[i][j]+1 << " ";
  70.         }
  71.         cout << endl;
  72.     }
  73.     BFS(2);
  74.  
  75. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement