I have to write SML code to solve knight's tour problem in backtracking. The chess knight must run all over the chessboard (size: NxN
) and must visit each square exactly once (no need to come back in first square at the end).
I already write all the functions to create an empty board, to set or get squares in the board, to get list of possible knight next moves. But I have no idea on how to write the recursive function in SML (I know how to write this algorithm in C but not in SML).
Algorithm in C for a 8x8 chessboard
dl and dr are array : (delta to calculate next moves)
dl = [-2,-2, -1, 1, 2, 2, 1, -1]
dr = [-1, 1, 2, 2, 1, -1,-2, -2]
bool backtracking(int** board, int k /*current step*/, int line, int row, int* dl, int* dr) {
bool success = false;
int way = 0;
do {
way++;
int new_line = line + dl[way];
int new_row = row + dr[way];
if (legal_move(board, new_line, new_row)) {
setBoard(board,new_line, new_row,k); //write the current step number k in board
if (k < 64) {
success = backtracking(board, k+1, new_line, new_row, dl, dc);
if (!success) {
setBoard(board,new_line, new_row,0);
}
}
else
success = true;
}
} while(!(success || way = 8));
return success;
}