2

BFSを使用して検索を実装したい。アルゴリズムによると、FIFO効果を得るにはキューを使用する必要があります。クリス・オカサキの純粋関数型データ構造の本を読んで、キューを作成する方法を見つけました(F#を使用して作成しました):

type 'a queue = 'a list * 'a list
let emtpy = [],[]
let isEmpty = function
    | [],_ -> true
    | _ -> false

let checkf = function
    | [],r -> List.rev r,[]
    | q -> q

let snoc (f,r) x = checkf (f,x :: r)

let head = function
    | ([],_) -> failwith "EMPTY"
    | (x::f,r) -> x

let tail = function
    | ([],_) -> failwith "EMPTY"
    | (x::f,r) -> checkf (f,r)

これをBFSに実装する方法を知っている人はいますか?

そして私はリストからツリーを作るためにこのコードを持っています:

let data = [4;3;8;7;10;1;9;6;5;0;2]

type Tree<'a> = 
    | Node of Tree<'a> * 'a * Tree<'a>
    | Leaf

let rec insert tree element = 
    match element,tree with
    | x,Leaf        -> Node(Leaf,x,Leaf)
    | x,Node(l,y,r) when x <= y -> Node((insert l x),y,r)
    | x,Node(l,y,r) when x > y -> Node(l,y,(insert r x))
    | _ -> Leaf

let makeTree = List.fold insert Leaf data

(これら2つのコードを組み合わせたい)

4

1 に答える 1

3

BFSアルゴリズムは次のとおりです。

Initialise the search by placing the starting vertex in the queue.
While the queue is not empty.
  Remove the front vertex from the queue.
  If this is a solution then we're finished -- report success.
  Otherwise, compute the immediate children of this vertex and enqueue them.
Otherwise we have exhausted the queue and found no solution -- report failure.

私のF#構文は少し不安定ですが、ソリューションをスケッチする方法は次のとおりです。

bfs start = bfsLoop ([start], [])

bfsLoop q0 =
  if   isEmpty q0
  then failWith "No solution"
  else v = head q0
       if   isSolution v
       then v
       else q1 = tail q0
            vs = childrenOf v
            q = foldl snoc vs q1
            bfsLoop q

お役に立てれば。

于 2011-05-20T06:31:20.687 に答える