質問はここに記載されています:Knight's Shortest Path Chess Question。チェスボードパズルでナイトの最短経路にOCaml再帰的ソリューションのスタックオーバーフロー
let is_in_list x s = List.exists (fun y -> if y = x then true else false) s;; (* find out if an element belongs to a list *)
let next_step n = [n+10;n-6;n+6;n-10;n+17;n-17;n+15;n-15];;
let rec legal_next_step = function
|[]->[]
|x::s->
if x<0 or x>63 then legal_next_step s
else x::legal_next_step s;;
let find_next_step n = legal_next_step (next_step n);; (* here is to find all the valid next moves and put them into a list*)
let rec min s =
let rec loop result = function
|[]->result;
|x::s->
if x < result then loop x s
else loop result s in
loop (List.hd s) s;;
let rec find_shortest_path n m =
if is_in_list m (next_step n) then 1
else
1 + min (List.map (fun x -> find_shortest_path x m) (find_next_step n)) ;;
これは、「スタックオーバーフロー」の問題を引き起こします。これは、次のような直感的な再帰的な方法を使用して解決しようとしました。何故ですか?私のプログラムはスタック内で再帰呼び出しのレイヤーを非常に多く作成していますか?または、私のコードで何かがひどく間違っています。そして、これらすべての結果の最小値を計算する -
非常に徹底的な説明!!!本当にありがとう!!!!!! – lkahtz