Advertisement
karbaev

BFS

Mar 28th, 2016
163
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.10 KB | None | 0 0
  1. #include "stdafx.h"
  2. #include <iostream>
  3. using namespace std;
  4. const int n=4;
  5. int i, j;
  6. //матрица смежности графа
  7. int GM[n][n] =
  8. {
  9. {0, 1, 1, 0},
  10. {0, 0, 1, 1},
  11. {1, 0, 0, 1},
  12. {0, 1, 0, 0}
  13. };
  14.  
  15. //поиск в ширину
  16. void BFS(bool *visited, int unit){
  17.   int *queue=new int[n];
  18.   int count, head;
  19.   for (i=0; i<n; i++) queue[i]=0;
  20.   count=0; head=0;
  21.   queue[count++]=unit;
  22.   visited[unit]=true;
  23.   while (head<count){
  24.     unit=queue[head++];
  25.     cout<<unit+1<<" ";
  26.     for (i=0; i<n; i++)
  27.       if (GM[unit][i] && !visited[i]){
  28.         queue[count++]=i;
  29.         visited[i]=true;
  30.     }
  31.   }
  32.   delete []queue;
  33. }
  34.  
  35. //главная функция
  36. void main(){
  37.   setlocale(LC_ALL, "Rus");
  38.   int start;
  39.   cout<<"Стартовая вершина >> "; cin>>start;
  40.   bool *visited=new bool[n];
  41.   cout<<"Матрица смежности графа: "<<endl;
  42.   for (i=0; i<n; i++){
  43.     visited[i]=false;
  44.     for (j=0; j<n; j++)
  45.       cout<<" "<<GM[i][j];
  46.       cout<<endl;
  47.    }
  48.   cout<<"Порядок обхода: ";
  49.   BFS(visited, start-1);
  50.  delete []visited;
  51. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement