美文网首页Haskell
[Haskell] 图的表示方法:邻接表

[Haskell] 图的表示方法:邻接表

作者: 何幻 | 来源:发表于2017-03-27 10:10 被阅读37次

1. 图的表示

import Data.Array
import Data.Ix

-- adjacency list representation
type Graph n w = Array n [(n, w)]

mkGraph :: (Ix n, Num w) => Bool -> (n, n) -> [(n, n, w)] -> (Graph n w)
mkGraph dir bnds es = 
    accumArray (\xs x -> x:xs) [] bnds
               ([(x1, (x2, w)) | (x1, x2, w) <- es] ++
                if dir then []
                else [(x2, (x1, w)) | (x1, x2, w) <- es, x1 /= x2])

adjacent :: (Ix n, Num w) => (Graph n w) -> n -> [n]
adjacent g v = map fst $ g!v

nodes :: (Ix n, Num w) => (Graph n w) -> [n]
nodes g = indices g

edgeIn :: (Ix n, Num w) => (Graph n w) -> (n, n) -> Bool
edgeIn g (x, y) = elem y $ adjacent g x

weight :: (Ix n, Num w) => n -> n -> (Graph n w) -> w
weight x y g = head [c | (a, c) <- g!x, a == y]

edgesD :: (Ix n, Num w) => (Graph n w) -> [(n, n, w)]
edgesD g = [(v1, v2, w) | v1 <- nodes g, (v2, w) <- g!v1]

edgesU :: (Ix n, Num w) => (Graph n w) -> [(n, n, w)]
edgesU g = [(v1, v2, w) | v1 <- nodes g, (v2, w) <- g!v1, v1 < v2]

2. 用例

testGraph = mkGraph False (1, 5) 
                  [(1, 2, 12), (1, 3, 34), (1, 5, 78),
                   (2, 4, 55), (2, 5, 32), (3, 4, 61),
                   (3, 5, 44), (4, 5, 93)]
                   
testAdjacent = adjacent testGraph 1
-- [5,3,2]

testNodes = nodes testGraph 
-- [1,2,3,4,5]

testEdgeIn = edgeIn testGraph (1, 2)
-- True

testWeight = weight 1 2 testGraph
-- 12

testEdgesD = edgesD testGraph
-- [(1,5,78),(1,3,34),(1,2,12),(2,1,12),(2,5,32),(2,4,55),(3,1,34),(3,5,44),(3,4,61),(4,3,61),(4,2,55),(4,5,93),(5,4,93),(5,3,44),(5,2,32),(5,1,78)]

testEdgesU = edgesU testGraph
-- [(1,5,78),(1,3,34),(1,2,12),(2,5,32),(2,4,55),(3,5,44),(3,4,61),(4,5,93)]

参考

Algorithms: A Functional Programming Approach

相关文章

  • [Haskell] 图的表示方法:邻接表

    1. 图的表示 2. 用例 参考 Algorithms: A Functional Programming App...

  • 图和树

    图 图的两种表示方法:邻接表和邻接矩阵,既可以表示有向图,也可以表示无向图 通常使用邻接表表示法,这种方法表示稀疏...

  • 图的表示和存储结构

    图的表示:两种表示方法 邻接矩阵和邻接表 无向图 有向图 图的权 连通图 度 图的存储结构 1、邻接矩阵存储 浪...

  • graph 图类

    1 表示方法 有许多种方式来表示图,这里我用邻接表来表示。邻接表由图中每个顶点的相邻顶点列表组成。 vertice...

  • [Haskell] 图的表示方法:邻接矩阵

    1. 图的表示 2. 用例 参考 Algorithms: A Functional Programming App...

  • 图 - Graph

    基本概念 边(Edge) 顶点(Vertex) 度(Degree) 图的表示邻接矩阵:用来表示稠密图邻接表:表示稀...

  • 图的表示-邻接矩阵与邻接表代码实现(2)

    由上篇图--图论基础(1) - 简书可知,邻接表适合表示稀疏图,邻接矩阵适合表示稠密图。 接下来我们用Java来表...

  • 图论基础

    图的表示有两种: 邻接矩阵(Adjacency Matrix)和邻接表(Adjacency Lists) 1、邻接...

  • 挑战程序设计竞赛11.5

    今天读了挑战程序设计竞赛的2.5,介绍了图的一些概念。 图的表示方法,邻接矩阵和邻接表。 邻接矩阵可以简单地建一个...

  • 12.有权图

    有权图 一、有权图的表示 1). 稠密图的实现表示 邻接矩阵中存对应的权值 2). 稀疏图的实现表示 邻接表中要存...

网友评论

    本文标题:[Haskell] 图的表示方法:邻接表

    本文链接:https://www.haomeiwen.com/subject/txglottx.html