var steps = [{ x:-2, y:1}, {x:-1, y:2}, {x:1, y:2}, {x:2, y:1},
{x:2, y:-1}, {x:1, y:-2}, {x:-1, y:-2}, {x:-2, y:-1}];
var chessboard = getNewChessboard();
var curstep = 1;
var knightTour = function(coord){
var next = { x: 0, y: 0};
chessboard[coord.x][coord.y] = curstep++;
if(curstep > 64) {
printBoard(); // 找到解答, 顯示棋盤
return true;
}else{
for(var i = 0; i < 8; i++){ // 每個點可能有8種走法
next.x = coord.x + steps[i].x;
next.y = coord.y + steps[i].y;
// 檢查下一步的位置會不會超出棋盤,或是否已走過
if(next.x >= 0 && next.x <=7 && next.y >= 0 && next.y <= 7
&& chessboard[next.x][next.y] == 0)
{
if(knightTour(next))
return true;
}
}
chessboard[coord.x][coord.y] = 0;
curstep--;
return false;
}
};