I want to solve a chess knight puzzle (it is for the testament of sherlok holmes game )
I have a 8x8 size chess board and the knight starts at (0,0). I got to find a sequence of moves to cover every spot on the chess board. (I suppose everyone knows the actual knight allowed movement in chess)
Here is my code, but I can't find what is wrong with it. Looking at the output, after some moves it sometimes chooses the wrong square to move to ...
<?php echo "\n - Knight puzzle brute forcer by VGA - \n"; $currpos = array(0,0); $occupiedpositions = array(); $validpositions = getvalidmoves($currpos, $occupiedpositions); print_r ($validpositions); function getvalidmoves($currpos, $occupiedpositions) { $validpositions = array( array($currpos[0]+1,$currpos[1]-2), array($currpos[0]+2,$currpos[1]-1), array($currpos[0]+2,$currpos[1]+1), array($currpos[0]+1,$currpos[1]+2), array($currpos[0]-1,$currpos[1]+2), array($currpos[0]-2,$currpos[1]+1), array($currpos[0]-1,$currpos[1]-2), array($currpos[0]-2,$currpos[1]-1) ); foreach ($validpositions as $key => $pos) { if (($pos[0] < 0) || ($pos[0] > 7) || ($pos[1] < 0) || ($pos[1] > 7) || in_array($pos,$occupiedpositions)) { unset($validpositions[$key]); } } if (sizeof($validpositions) > 0) { if (sizeof($occupiedpositions) == 62) { echo "SUCCESS !!!!!!!\n"; print_r ($occupiedpositions); exit; } } else { echo "FAILURE after ",sizeof($occupiedpositions)," moves \n"; return; } foreach ($validpositions as $key => $pos) { array_push($occupiedpositions,$currpos); $currpos = $pos; getvalidmoves($currpos, $occupiedpositions); } return; } ?>