fork download
  1. #include <stdio.h>
  2. #include <string.h>
  3. #define SIZE 50
  4.  
  5.  
  6. void bfs(int matrix[][SIZE], int nodes, int start) {
  7.  
  8. int queue[nodes],
  9. i, j,
  10. visited[nodes],
  11. first = 0,
  12. last = 0,
  13. curr;
  14.  
  15. queue[ first ] = start;
  16.  
  17. memset(visited, 0, sizeof(visited));
  18.  
  19. visited[ start ] = 1;
  20.  
  21. while(first <= last) {
  22.  
  23. curr = queue[first];
  24.  
  25. for(j = 1; j <= nodes; ++j)
  26.  
  27. if(0 == visited[j] && 1 == matrix[curr][ j ]) {
  28.  
  29. last = last + 1;
  30.  
  31. queue[ last ] = j;
  32.  
  33. visited[ j ] = 1;
  34. }
  35.  
  36. first++;
  37. }
  38.  
  39. for(i = 0 ; i < nodes; ++i) printf("%d ", queue[i]);
  40. }
  41.  
  42. void display(int mat[][SIZE], int nodes) {
  43.  
  44. for(int i = 1; i <= nodes; ++i) {
  45.  
  46. for(int j = 1; j <= nodes; ++j) {
  47.  
  48. printf("%d ", mat[i][j]);
  49.  
  50. }
  51. printf("\n");
  52. }
  53. }
  54.  
  55.  
  56. int main(int argc, char const *argv[])
  57. {
  58.  
  59. int matrix[SIZE][SIZE],
  60.  
  61. nodes, edges, s, i, j;
  62.  
  63. scanf("%d %d", &nodes, &edges);
  64.  
  65. while(edges--) {
  66.  
  67. scanf("%d %d", &i, &j);
  68.  
  69. matrix[i][j] = 1;
  70. }
  71.  
  72. display(matrix, nodes);
  73.  
  74. bfs(matrix, nodes, 4);
  75.  
  76. return 0;
  77. }
Success #stdin #stdout 0s 4552KB
stdin
5 7
1 2
2 1
2 2
2 5
3 2
4 5
5 3
stdout
0 1 0 0 0 
1 1 0 0 1 
0 1 0 0 0 
0 0 0 0 1 
0 0 1 0 0 
4 5 3 2 1