#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
#define N 5

int cost[N][N], list[N];

void pp(int *a, int i, int j)
{
  for (int ii = 0; ii < i; ++ii) {
    for (int jj = 0; jj < j; ++jj)
      printf("%12d", *a++);
    printf("\n");
  }
}

int visitedCheck(int n)
{
  // printf("n = %d\n", n);
  // pp(list, 1, 5);
  for (int i = 1; i < N; ++i)if (list[i] == n)return 1;
  return 0;
}

int main(void)
{
  // test data making
  for (int i = 0; i < N; ++i)
    for (int j = 0; j < i; ++j)
      cost[i][j] = cost[j][i] = (rand() % 20 + 2);
  // pp(*cost, 5, 5);

  for (int i = 0; i < N; ++i)list[i] = 0;

  int pos = 0;
  for (int seq = 1; seq < N; ++seq) {
    int min = INT_MAX, nextPos = pos;
    for (int i = 1; i < N; ++i) {
      if (!(visitedCheck(i)) && (min > cost[pos][i])) {
        min = cost[pos][i];
        nextPos = i;
      }
    }
    list[seq] = nextPos;
    pos = nextPos;
  }
  printf("result = ");
  pp(list, 1, 5);
  return 0;
}
