fork download
  1. //Depth First Search Traversal
  2. #include <stdio.h>
  3. #include <memory.h>
  4. #define FIN "graph.in"
  5. #define FOUT "bfs.out"
  6. #define DIM 30
  7.  
  8. int matrix[DIM][DIM], nodes,
  9. i, j,
  10. explored[DIM];
  11.  
  12. void dfs(int node) {
  13.  
  14. printf("%d ", node + 1);
  15.  
  16. explored[node] = 1;
  17.  
  18. for(int i = 0; i <nodes;++i) {
  19.  
  20. if(matrix[node][i] == 1 && explored[i] == 0) {
  21.  
  22. dfs(i);
  23. }
  24. }
  25. }
  26.  
  27. int main(int argc, char const *argv[]) {
  28.  
  29. //freopen(FIN, "r", stdin);
  30. int startNode;
  31. //freopen(FOUT, "w", stdout);
  32. scanf("%d", &nodes);
  33.  
  34. for(i = 0; i < nodes; ++i) {
  35. for(j = 0; j < nodes; ++j) {
  36. scanf("%d", &matrix[i][j]);
  37. }
  38. }
  39.  
  40. //Display matrix adjcency
  41.  
  42. for(i = 0; i < nodes; ++i) {
  43. for(j = 0; j < nodes; ++j) {
  44. printf("%d ", matrix[i][j]);
  45. }
  46. printf("\n");
  47. }
  48.  
  49. startNode = 1;
  50.  
  51. dfs( startNode );
  52.  
  53. return 0;
  54. }
Success #stdin #stdout 0s 5312KB
stdin
8
0 1 1 0 0 0 0 0
1 0 1 1 0 0 0 0
1 1 0 1 1 1 0 1
0 1 1 0 1 0 1 0
0 0 1 1 0 1 1 0
0 0 1 0 1 0 1 1
0 0 0 0 1 1 0 1
0 0 1 0 0 1 1 0
stdout
0 1 1 0 0 0 0 0 
1 0 1 1 0 0 0 0 
1 1 0 1 1 1 0 1 
0 1 1 0 1 0 1 0 
0 0 1 1 0 1 1 0 
0 0 1 0 1 0 1 1 
0 0 0 0 1 1 0 1 
0 0 1 0 0 1 1 0 
2 1 3 4 5 6 7 8