fork download
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <limits.h>
  4. #define N 5
  5.  
  6. int cost[N][N], list[N];
  7.  
  8. void pp(int *a, int i, int j)
  9. {
  10. for (int ii = 0; ii < i; ++ii) {
  11. for (int jj = 0; jj < j; ++jj)
  12. printf("%12d", *a++);
  13. printf("\n");
  14. }
  15. }
  16.  
  17. int visitedCheck(int n)
  18. {
  19. // printf("n = %d\n", n);
  20. // pp(list, 1, 5);
  21. for (int i = 1; i < N; ++i)if (list[i] == n)return 1;
  22. return 0;
  23. }
  24.  
  25. int main(void)
  26. {
  27. // test data making
  28. for (int i = 0; i < N; ++i)
  29. for (int j = 0; j < i; ++j)
  30. cost[i][j] = cost[j][i] = (rand() % 20 + 2);
  31. // pp(*cost, 5, 5);
  32.  
  33. for (int i = 0; i < N; ++i)list[i] = 0;
  34.  
  35. int pos = 0;
  36. for (int seq = 1; seq < N; ++seq) {
  37. int min = INT_MAX, nextPos = pos;
  38. for (int i = 1; i < N; ++i) {
  39. if (!(visitedCheck(i)) && (min > cost[pos][i])) {
  40. min = cost[pos][i];
  41. nextPos = i;
  42. }
  43. }
  44. list[seq] = nextPos;
  45. pos = nextPos;
  46. }
  47. printf("result = ");
  48. pp(list, 1, 5);
  49. return 0;
  50. }
  51.  
Success #stdin #stdout 0s 2248KB
stdin
Standard input is empty
stdout
result =            0           1           4           3           2