#include <stdio.h>

#define CELLS 18
#define WIN 14

using namespace std;

int grid[][5] = {
{1,1,1,1,1},
{1,1,0,0,0},
{1,0,0,1,1},
{1,1,0,0,1},
{1,1,1,1,1}
};

int spots[CELLS];

int used[CELLS];

void use(int value, int which) {
  used[value] = which;
}

void reclaim(int value, int which) {
  used[value] = -1;
}

bool unused(int value) {
  return (used[value] == -1);
}

int distanc(int v1, int v2) {
  int x1 = spots[v1] / 5;
  int x2 = spots[v2] / 5;
  int y1 = spots[v1] % 5;
  int y2 = spots[v2] % 5;
  int dx = (x1 - x2);
  int dy = (y1 - y2);
  return (dx * dx + dy * dy);
}

void print() {
  for (int row=0;row<5;++row) {
    for (int col=0;col<5;++col) {
      bool printed = false;
      for (int i=0;i<CELLS;i++) {
        if (spots[i] == row*5 + col) {
          if (used[i] == -1) {
            printf("XX ");
          } else {
            printf("%02d ", used[i]+1);
          }
          printed = true;
        }
      }
      if (!printed) {
        printf("   ");
      }
    }
    printf("\n");
  }
  printf("--------------\n");
}

void recurse(int which, int last, int distance) {
  if (which == WIN) {
    print();
  } else if (which == 0) {
    for (int i=0;i<CELLS;++i) {
      use(i,which);
      recurse(which+1, i, 0);
      reclaim(i,which);
    }
  } else {
    for (int i=0;i<CELLS;++i) {
      if (unused(i) && (distance < distanc(last, i))) {
        use(i,which);
        recurse(which+1, i, distanc(last, i));
        reclaim(i,which);
      }
    }
  }
}

int main() {
  int cur=0;
  for (int row=0;row<5;++row) {
    for (int col=0;col<5;++col) {
      if (grid[row][col] == 1) {
        spots[cur++] = row*5+col;
      }
    }
  }
  for (int i=0;i<CELLS;++i) {
    used[i] = -1;
  }
  recurse(0,-1,0);
}
