F# 实现图的深度遍历

下面是图中的深度遍历F# 版本,如果有问题还请各位看官不要吝啬指正:)。

Graph类在我之前的随笔中已经定义过了,这边直接使用了。

type GraphOperations(graph : Graph) =

    ///depth-first traversal 
    member this.DFSTraverse(action : unit -> unit, startNodeId : string, endNodeId : string) =  
        let visited : string array = Array.zeroCreate graph.Nodes.Length 
        let visitIndex = ref 0              
        let rec dfsTraverse(nodeId : string) =                        
            match nodeId with 
            | found when nodeId = endNodeId ->                                       
                    action()
            | _ ->           
                    visited.[!visitIndex] <- nodeId                   
                    visitIndex := !visitIndex + 1
                    let node = ref Unchecked.defaultof<Node>
                    try
                        node := graph.Nodes |> List.find(fun item -> item.ID = nodeId)                        
                    with
                        | _ -> printfn "There is no such node"
                    if ((!node).OutgoingEdges.Length = 0) then
                        ()
                    else                   
                        for i in [0..((!node).OutgoingEdges.Length - 1)] do
                            if ( visited |> Array.exists(fun x -> x = (!node).OutgoingEdges.[i].ToNode.ID)) then
                                ()
                            else
                                dfsTraverse((!node).OutgoingEdges.[i].ToNode.ID)                                          
        dfsTraverse(startNodeId)

代码中的action参数为用户自定义参数,只不过我将其参数类型和返回指固定了,这样不好,在实际情况中要做相应的改动。做个笔记:)

posted @ 2012-11-08 15:18  ZackZhou  阅读(257)  评论(0编辑  收藏  举报