fork(2) download
  1. #include <bits/stdc++.h>
  2. #define inf 1e9
  3. using namespace std;
  4.  
  5. int dist[2010];
  6. vector<int> adj[2010];
  7.  
  8. bool bfs( int x )
  9. {
  10. queue<int>q;
  11. q.push(x);
  12.  
  13. memset( dist, -1, sizeof(dist) );
  14. dist[x]= 0;
  15.  
  16. while(!q.empty())
  17. {
  18. int u= q.front();
  19. q.pop();
  20.  
  21. for( int i=0; i<adj[u].size(); i++ )
  22. {
  23. int v= adj[u][i];
  24.  
  25. if( dist[v]==-1 )
  26. {
  27. dist[v]= dist[u]+1;
  28. q.push(v);
  29. }
  30.  
  31. else if( dist[v]!=-1 and v==x )
  32. {
  33. dist[v]= dist[u]+1;
  34. return 1;
  35. }
  36. }
  37. }
  38.  
  39. return 0;
  40. }
  41.  
  42. int main()
  43. {
  44. int n;
  45. cin>>n;
  46.  
  47. for(int i=0; i<n; i++)
  48. for(int j=0; j<n; j++)
  49. {
  50. int p;
  51. scanf("%d", &p);
  52.  
  53. if(p)
  54. adj[i].push_back(j);
  55. }
  56.  
  57. for( int i=0; i<n; i++ )
  58. {
  59. if( bfs(i) )
  60. printf("%d\n", dist[i]);
  61. else
  62. printf("NO WAY\n");
  63. }
  64. }
  65.  
Success #stdin #stdout 0s 15288KB
stdin
Standard input is empty
stdout
Standard output is empty