PDA

View Full Version : [c] euristica accessibilità (giro del cavallo)


Alex_G
07-06-2013, 18:42
Ciao a tutti, il problema mi chiedeva di far fare il "giro del cavallo", ossia far passare il cavallo degli scacchi in ogni casella della scacchiera, senza tornare due volte sulla stessa casella; mi è stato richiesto di utilizzare l'euristica dell'accessibilità, cioè di calcolare per ogni casella da quante altre caselle fosse raggiungibile, in modo tale da far muovere il cavallo nelle caselle più "difficili" da raggiungere lasciando come ultime mosse quelle più facili. Eseguendo il programma Windows smette di funzionare... :muro: riuscite ad individuare il problema ? #include<stdio.h>
#include<stdlib.h>
#define DIM 8
#define IN_BOUNDS(x) ((x) >= 0 && (x) < DIM)

int move(int, int);
void showBoard(void);

int accessibility[DIM][DIM] = {{2,3,4,4,4,4,3,2},{3,4,6,6,6,6,4,3}, {4,6,8,8,8,8,6,4}, {4,6,8,8,8,8,6,4}, {4,6,8,8,8,8,6,4}, {4,6,8,8,8,8,6,4}, {3,4,6,6,6,6,4,3}, {2,3,4,4,4,4,3,2} };
int board[DIM][DIM] = { 0 };
int horizontal[DIM] = { 2, 1, -1, -2, -2, -1, 1, 2 };
int vertical[DIM] = { -1, -2, -2, -1, 1, 2, 2, 1 };
int tentativi[DIM] = {0};

int main()
{
int currentRow = 0, currentColumn = 0, moveNumber, count = 1;

do
{
moveNumber = move(currentRow, currentColumn);

if(moveNumber != -1)
{
currentRow += vertical[ moveNumber ];
currentColumn += horizontal[ moveNumber ];
board[ currentRow ][ currentColumn ] = 1;
count++;
}

} while(moveNumber != -1);

printf("%d\n", count);
showBoard();

return 0;
}

int move(int currentRow, int currentColumn)
{
int moveNumber;
int jontatore;
int contatore_valore_minore;

for (moveNumber = 0; moveNumber < DIM; moveNumber++) {
int tempRow = currentRow + vertical[ moveNumber ];
int tempColumn = currentColumn + horizontal[ moveNumber ];

if (IN_BOUNDS(tempRow) && IN_BOUNDS(tempColumn) && (board[ tempRow ][ tempColumn ] == 0))
{
tentativi[moveNumber] = accessibility[tempRow][tempColumn];
}

}
for (jontatore=0;jontatore<8;jontatore++) {
if (tentativi[jontatore]>tentativi[jontatore+1] && tentativi[jontatore+1] != 0 ){
contatore_valore_minore = jontatore+1;
}
}
if (tentativi[0]==0 && tentativi[1]==0 && tentativi[2]==0 && tentativi[3]==0 && tentativi[4]==0 && tentativi[5]==0 && tentativi[6]==0 && tentativi[7]==0 )
return -1;
else
return contatore_valore_minore;
}

void showBoard(void)
{
int i, j;

for(i = 0; i < DIM; ++i)
{
for(j = 0; j < DIM; ++j)
printf("%d\t", board[ i ][ j ]);

printf("\n");

}
}