sml - open knight's tour (backtracking) algorithm in smlnj -


i have write sml code solve knight's tour problem in backtracking. chess knight must run on chessboard (size: nxn) , must visit each square once (no need come in first square @ end).

i write functions create empty board, set or squares in board, list of possible knight next moves. have no idea on how write recursive function in sml (i know how write algorithm in c not in sml).

algorithm in c 8x8 chessboard

dl , dr array : (delta 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 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;     } 

don't think c! that's nasty way of thinking! working out algorithm in c/imperative never helpful. need homework , learn think properly.

how design program? has store state, , each state has record knight has gone. design state tuple of board (a list of list of bool recording squares traversed) , moves (a list of (int, int)). so, function calls this:

exception fun iter (state, []) =        if boardfull state state else raise   | iter (state, next::ns) =       iter (next, states next) handle => iter (state, ns)  fun states (board, ps) =     <a move pair (int, int); write out list of 8 moves; map next fn down list, , filter legal moves> (2 or 3 lines of code write) fun boardfull (board, pos::ps) = <foldl twice apply 'and' fn on whole board> (1 line of code write) 

Comments

Popular posts from this blog

php - What is the difference between $_SERVER['PATH_INFO'] and $_SERVER['ORIG_PATH_INFO']? -

fortran - Function return type mismatch -

queue - mq_receive: message too long -