1 // jumpsaround - jumper game
    2 // (c) 2011 Alexander Kulbartsch
    3 
    4 #include <stdio.h>
    5 
    6 #define SIZEX 6
    7 #define SIZEY 5
    8 
    9 static signed int jump[8][2] = {{-1,-2}, {1,-2}, {-2,-1}, {2,-1}, {-2,1}, {2,1}, {-1,2}, {1,2}}; 
   10 
   11 char board[SIZEX][SIZEY];
   12 char iters[SIZEX*SIZEY];
   13 long int solutions; 
   14 long int roundtrips;
   15 
   16 void jumpto(signed char x, signed char y, int iter, char arity);
   17 void printboard();
   18 
   19 
   20 int main (int argc, const char * argv[]) {
   21     printf("Hello, Jumper!\n");
   22     
   23     // init
   24     for (int i = 0; i < SIZEX; i++) {
   25         for (int j = 0; j < SIZEY; j++) {
   26             board[i][j] = 0;
   27         }
   28     }
   29     for (int i = 0; i < (SIZEX*SIZEY); i++) iters[i] = 0;
   30     iters[0] = ' ';
   31 
   32     jumpto(0, 0, 1, 0);
   33     
   34     printf("I am done.\n");
   35     
   36     return 0;
   37 }
   38 
   39 
   40 void jumpto(signed char x, signed char y, int iter, char arity) {
   41 
   42     // check if position is on the board
   43     if ( x<0 || x>(SIZEX-1) || y<0 || y>(SIZEY-1) ) return;
   44     
   45     // check if field on board is still empty
   46     if ( board[x][y] != 0 ) return;
   47 
   48     // ok - store position
   49     board[x][y] = iter;
   50     iters[iter] = arity + '0';
   51     
   52     // finished?
   53     if (iter >= SIZEX*SIZEY ) {
   54 
   55         // check for jumper roundtrips
   56         signed int round = 0;
   57         for (int i = 0; i < 8; i++) {
   58             signed char nx = x + jump[i][0]; 
   59             signed char ny = y + jump[i][1];
   60             // check if position is on the board
   61             if ( nx<0 || nx>(SIZEX-1) || ny<0 || ny>(SIZEY-1) ) continue;
   62             // detect roundtrip
   63             if ( board[nx][ny] == 1 ) { round = 1; roundtrips++; break; } // True
   64         }
   65         solutions++;
   66         printboard(round);
   67 
   68         // end this iteration
   69         board[x][y] = 0;
   70         iters[iter] = 0;
   71         return;
   72     }
   73     
   74     // try next jump
   75     for (int i = 0; i < 8; i++) {
   76         signed char nx = x + jump[i][0]; 
   77         signed char ny = y + jump[i][1]; 
   78         jumpto(nx, ny, iter + 1, i);
   79     }
   80     
   81     // this iteration is done
   82     board[x][y] = 0;
   83     iters[iter] = 0;
   84     
   85 }
   86 
   87 void printboard(int round) {
   88     printf("===== Solution # %ld (Roundtripps: %ld) ====== ", solutions, roundtrips);
   89     if (round) printf(" *** Roundtrip *** ");
   90     printf("\n");
   91     for (int i = 0; i < SIZEY; i++) {
   92         for (int j = 0; j < SIZEX; j++) {
   93             printf("%2i:", board[j][i]);
   94         }
   95         printf("\n");
   96     }
   97     printf("\n");
   98 }
   99 
  100 // EOF