Giraffe.Graph (giraffe v0.1.3)

Public interface for working with graphs. Delegates to specific implementations based on whether the graph is directed or undirected.

Summary

Types

edge()

@type edge() :: {vertex(), vertex(), weight()}

t()

@type t() :: %Giraffe.Graph{
  impl: Giraffe.Graph.Directed.t() | Giraffe.Graph.Undirected.t(),
  type: :directed | :undirected
}

vertex()

@type vertex() :: any()

weight()

@type weight() :: number()

Functions

add_edge(graph, from, to, weight \\ 1)

@spec add_edge(t(), vertex(), vertex(), weight()) :: t()

add_vertex(graph, vertex)

@spec add_vertex(t(), vertex()) :: t()

edges(graph)

@spec edges(t()) :: [edge()]

get_paths(graph, start, finish)

@spec get_paths(t(), vertex(), vertex()) :: [[vertex()]]

get_shortest_path(graph, start, finish)

@spec get_shortest_path(t(), vertex(), vertex()) :: [vertex()] | nil

new(list)

@spec new([{:type, :directed}]) :: t()
@spec new([{:type, :undirected}]) :: t()

Creates a new graph.

Options

  • :type - The type of graph. Can be :directed or :undirected. Defaults to :directed.

Examples

iex> Giraffe.Graph.new(type: :directed)
%Giraffe.Graph{impl: %Giraffe.Graph.Directed{vertices: MapSet.new([]), edges: %{}}, type: :directed}

iex> Giraffe.Graph.new(type: :undirected)
%Giraffe.Graph{impl: %Giraffe.Graph.Undirected{vertices: MapSet.new([]), edges: %{}}, type: :undirected}

reachable(graph, vertices)

@spec reachable(t(), [vertex()]) :: [vertex()]

Returns a list of vertices that are reachable from any of the given vertices.

Includes the starting vertices themselves as paths of length zero are allowed.

Examples

iex> g = Giraffe.Graph.new(type: :directed)
...> g = g |> Giraffe.Graph.add_edge(1, 2) |> Giraffe.Graph.add_edge(2, 3)
...> Giraffe.Graph.reachable(g, [1])
[1, 2, 3]

iex> g = Giraffe.Graph.new(type: :undirected)
...> g = g |> Giraffe.Graph.add_edge(1, 2) |> Giraffe.Graph.add_edge(2, 3)
...> Giraffe.Graph.reachable(g, [3])
[1, 2, 3]

vertices(graph)

@spec vertices(t()) :: [vertex()]