fork download
  1. #include <iostream>
  2. #include <queue>
  3. using namespace std;
  4.  
  5. int main() {
  6. int n, x, y, v;
  7. cin >> n;
  8. int matrix[n + 1][n + 1], dist[n + 1];
  9. queue <int> plan;
  10. for (int i = 1; i <= n; i++)
  11. for (int j = 1; j <= n; j++)
  12. cin >> matrix[i][j];
  13. cin >> x >> y;
  14. for (int i = 1; i <= n; i++)
  15. dist[i] = -1;
  16. plan.push(x);
  17. dist[x] = 0;
  18. while (!plan.empty()) {
  19. v = plan.front();
  20. plan.pop();
  21. for (int i = 1; i <= n; i++) {
  22. if (dist[i] == -1 && matrix[v][i]) {
  23. plan.push(i);
  24. dist[i] = dist[v] + 1;
  25. }
  26. }
  27. if (v == y) plan.empty(); // если обработали вершину y, прекращаем обход
  28. }
  29. cout << dist[y];
  30. return 0;
  31. }
Success #stdin #stdout 0s 15240KB
stdin
6
0 1 1 1 0 1
1 0 0 0 0 0 
1 0 0 0 0 0
1 0 0 0 0 0 
0 0 0 0 0 0
1 0 0 0 0 0
5 2
stdout
-1