Advertisement
MeShootIn

BFS

Oct 22nd, 2016
79
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.80 KB | None | 0 0
  1. #include <cstdio>
  2. #include <vector>
  3. #include <queue>
  4. using namespace std;
  5. int main()
  6. {
  7.     int n, i, j, vBegin, vEnd, x, current;
  8.     scanf("%d", &n);
  9.     vector < vector <int> > list(n);
  10.     for(i = 0; i < n; i++)
  11.     {
  12.         for(j = 0; j < n; j++)
  13.         {
  14.             scanf("%d", &x);
  15.             if(x)
  16.             {
  17.                 list[i].push_back(j);
  18.                 list[j].push_back(i);
  19.             }
  20.         }
  21.     }
  22.     scanf("%d%d", &vBegin, &vEnd);
  23.     vBegin--, vEnd--;
  24.     queue <int> q;
  25.     q.push(vBegin);
  26.     vector <int> len(n, -1);
  27.     len[vBegin] = 0;
  28.     while(true)
  29.     {
  30.         if(q.empty())
  31.         {
  32.             printf("-1");
  33.             return 0;
  34.         }
  35.         current = q.front();
  36.         q.pop();
  37.         if(current == vEnd)
  38.         {
  39.             printf("%d", len[vEnd]);
  40.             return 0;
  41.         }
  42.         for(int next : list[current])
  43.         {
  44.             if(len[next] == -1)
  45.             {
  46.                 q.push(next);
  47.                 len[next] = len[current] + 1;
  48.             }
  49.         }
  50.     }
  51. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement