简体   繁体   中英

Haskell Prim's Algorithm

does anyone know how the change prim's algorithm so that is handle a graph that is not connected? I know I have to use a forest but I don't know how to implement that in Haskell..

`This is what I got

prim for            = prim' [n] ns [[]]
    where (n:ns)    = nodes for
        es          = edges for
        prim' t [] mst        = mst
        prim' t (r:rs) (x:xs) = let m = minimum[(c,u',v'| u <-t, v <- (r:rs), (u,v,c) <- es]
                    m | m == Nothing    = prim' (r:t) rs ([]:mst)
                      | otherwise       = prim' (v:t) (delete v' r) ((m:x):xs)

Prim's algorithm finds a MST, but if the graph is not connected no MST exist. You can check if your tree is a spanning tree if it has |V| - 1 elements it in.

It's easy to find the connected parts of the graph. Run Prim's algorithm for every connected sub-graph separately.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM