fork download
  1. #include <iostream>
  2. #include <queue>
  3. using namespace std;
  4. int graph[1001][1001], d[1001];
  5. queue <int> q;
  6.  
  7. int main() {
  8. ios_base::sync_with_stdio(false);
  9. cin.tie(NULL);
  10. int n, x, v;
  11. cin >> n >> x;
  12. x--;
  13. for (int i = 0; i < n; i++) {
  14. for (int j = 0; j < n; j++) {
  15. cin >> graph[i][j];
  16. }
  17. }
  18. for (int i = 0; i < n; i++) {
  19. d[i] = -1;
  20. }
  21. q.push(x);
  22. d[x] = 0;
  23. while (!q.empty()) {
  24. v = q.front();
  25. q.pop();
  26. for (int i = 0; i < n; i++) {
  27. if (d[i] == -1 && graph[v][i]) {
  28. q.push(i);
  29. d[i] = d[v] + 1;
  30. }
  31. }
  32. }
  33. for(int i = 0; i < n; i ++) {
  34. cout << d[i] << " ";
  35. }
  36. return 0;
  37. }
Success #stdin #stdout 0s 19152KB
stdin
3 1
0 0 0
0 1 0
1 1 1
stdout
0 -1 -1