Skip to content

Commit

Permalink
WIP on Prim algorithm.
Browse files Browse the repository at this point in the history
A total mess at the moment.
  • Loading branch information
sayoder committed Mar 20, 2017
1 parent 7d5f5af commit f00fa5b
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 10 deletions.
46 changes: 37 additions & 9 deletions src/Grasph/Algorithm/MWST.hs
Original file line number Diff line number Diff line change
Expand Up @@ -19,14 +19,42 @@ kruskal' (e:es) mwt = if acyclic mwtWithEdge
acyclic g = length (vertices g) == length (edges g) + 1

prim :: (Ord w) => Graph v w d -> Graph v w d
prim g = g {edges = prim' g g [] (lengthmap g)}
prim g = g {edges = prim' g [tail $ vertices g] [head $ vertices g] [] (lengthmap g)}

prim' :: (Ord w) => [v] -> [Edge v w d] -> Int -> M.Map v (Infinitable w)
prim' v v' t lv
| length v' == n = t
|
prim' :: (Ord w) => Graph v w d
-> [v] -- the set (V-V')
-> [v] -- V'
-> [Edge v w d] -- T
-> M.Map v (Infinitable w) -- L(v)
-> [Edge v w d]
prim' g unvisited v'@(u:us) t lv
| length v' == (length $ vertices g) = t
| otherwise = prim' g unvisited' v'' e:t lv'
where w = minWeightV [(v, fromJust (M.lookup lv v)) | v <- unvisited]
e = findEdge (u, w)

lengthmap :: (Ord w) => Graph v w d -> v -> M.Map v (Infinitable w)
lengthmap g v = fromList . map f $ edges g
where f edge =
adj = adjacencyList g v
lengthmap :: (Ord w) => Graph v w d
-> [v]
-> v
-> M.Map v (Edge v w d, Infinitable w)
lengthmap g vs u = fromList . map f $ vertices g
where f v= (v, dist g vs v)
adj = adjacencyList g u

dist :: Graph v w d -> v -> v -> Infinitable w
dist g u v = dist' (allEdges g) u v

-- Find the distance from a set of vertices to a given vertex
dist :: Graph v w d -> [v] -> v -> (v, Infinitable w)
dist g vset v' = dist' (allEdges g) vset v

dist' [] _ _ = PositiveInfinity
dist' es vset v' = tupleSndMin $ map (\v -> dist'' es v v')

dist'' :: [Edge v w d] -> v -> v -> (v, Infinitable w)
dist'' [] _ _ = PositiveInfinity
dist'' (e:es) u v
| endpoints e == (u,v) = Regular $ weight e
| otherwise = dist' es u v

tupleSndMin = foldl1 (\t1 t2 -> if (snd t1) < (snd t2) then t1 else t2)
4 changes: 3 additions & 1 deletion src/Grasph/Graph.hs
Original file line number Diff line number Diff line change
Expand Up @@ -183,10 +183,12 @@ reverseEdge e@(Edge (v1,v2) _ _) = e { endpoints=(v2,v1) }
reverseEdges :: Graph v w c -> [Edge v w c]
reverseEdges g = map reverseEdge $ edges g


allEdges :: Graph v w c -> [Edge v w c]
allEdges g = if directed g then edges g else edges g ++ reverseEdges g

findEdge :: Graph v w d -> (v,v) -> Edge v w d
findEdge g pair = head $ filter (\e -> endpoints e == pair) (edges g)

incidentEdges :: (Eq v) => Graph v w c -> v -> [Edge v w c]
incidentEdges g v = incidentEdges' (edges g) v []

Expand Down

0 comments on commit f00fa5b

Please sign in to comment.