Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
88 changes: 42 additions & 46 deletions doc/oper.xml
Original file line number Diff line number Diff line change
Expand Up @@ -1617,37 +1617,31 @@ true
</ManSection>
<#/GAPDoc>

<!-- TODO is it *the* lexicographically least shortest path? -->
<#GAPDoc Label="DigraphShortestPath">
<ManSection>
<Oper Name="DigraphShortestPath" Arg="digraph, u, v"/>
<Returns>A pair of lists, or <K>fail</K>.</Returns>
<Description>
Returns a shortest directed path in the digraph <A>digraph</A> from vertex
<A>u</A> to vertex <A>v</A>, if such a path exists. If <C><A>u</A> =
<A>v</A></C>, then the shortest non-trivial cycle is returned, again, if it
exists. Otherwise, this operation returns <K>fail</K>. See Section
<Ref Subsect="Definitions" Style="Text"/> for the definition of a directed
path and a directed cycle.
<P/>

See <Ref Oper="DigraphPath"/> for details on the output.
Returns the lexicographically least shortest directed path in the digraph
<A>digraph</A> from vertex <A>u</A> to vertex <A>v</A>, if such a path
exists. If <C><A>u</A> = <A>v</A></C> or no path exists, this operation
returns <K>fail</K>. See Section <Ref Subsect="Definitions" Style="Text"/>
for the definition of a directed path. See <Ref Oper="DigraphPath"/> for
details on the output. <P/>

The method for <C>DigraphShortestPath</C> has worst case complexity of
<M>O(m + n)</M> where <M>m</M> is the number of edges and <M>n</M> the
number of vertices in <A>digraph</A>.
number of vertices in <A>digraph</A>. <P/>

See <Ref Oper="DigraphShortestPaths"/>. See also the
weighted operation <Ref Oper="EdgeWeightedDigraphShortestPath"/>.
<Example><![CDATA[
gap> D := Digraph([[1, 2], [3], [2, 4], [1], [2, 4]]);
<immutable digraph with 5 vertices, 8 edges>
gap> DigraphShortestPath(D, 1, 1);
fail
gap> DigraphShortestPath(D, 5, 1);
[ [ 5, 4, 1 ], [ 2, 1 ] ]
gap> DigraphShortestPath(D, 3, 3);
[ [ 3, 2, 3 ], [ 1, 1 ] ]
gap> DigraphShortestPath(D, 5, 5);
fail
gap> DigraphShortestPath(D, 1, 1);
[ [ 1, 1 ], [ 1 ] ]
]]></Example>
</Description>
</ManSection>
Expand Down Expand Up @@ -2247,46 +2241,48 @@ false]]></Example>
</ManSection>
<#/GAPDoc>

<#GAPDoc Label="DigraphDijkstra">
<#GAPDoc Label="DigraphShortestPaths">
<ManSection>
<Oper Name="DigraphDijkstra" Arg="digraph, source, target"
Label="for a source and target"/>
<Oper Name="DigraphDijkstra" Arg="digraph, source" Label="for a source"/>
<Oper Name="DigraphShortestPaths" Arg="digraph, source"/>
<Returns>Two lists.</Returns>
<Description>
If <A>digraph</A> is a digraph and <A>source</A> and <A>target</A> are
vertices of <A>digraph</A>, then <C>DigraphDijkstra</C> calculates the
length of the shortest path from <A>source</A> to <A>target</A> and returns
two lists. Each element of the first list is the distance of the
corresponding element from <A>source</A>. If a vertex was not visited in
the process of calculating the shortest distance to <A>target</A> or if
there is no path connecting that vertex with <A>source</A>, then
the corresponding distance is <K>infinity</K>. Each element of the
second list gives the previous vertex in the shortest path
from <A>source</A> to the corresponding vertex. For
<A>source</A> and for any vertices that remained unvisited this
will be <C>-1</C>.<P/>

If the optional second argument <A>target</A> is not present, then
<C>DigraphDijkstra</C> returns the shortest path from <A>source</A> to
every vertex that is reachable from <A>source</A>.
If <A>digraph</A> is a digraph and <A>source</A> is a vertex of
<A>digraph</A>, then <C>DigraphShortestPaths</C> returns two lists,
<C>distances</C> and <C>parents</C>, describing the shortest paths from
<A>source</A> to every vertex in <A>digraph</A>. For a vertex <A>v</A>,
<C>distances[v]</C> is the shortest distance to <A>v</A>, and
<C>parents[v]</C> is the final vertex before <C>v</C> on the shortest path
from <A>source</A> to <C>v</C>. <P/> If a vertex is unreachable from
<A>v</A>, then its distance is <K>infinity</K>, and its parent is <C>-1</C>.
<P/>

<Example><![CDATA[
gap> mat := [[0, 1, 1], [0, 0, 1], [0, 0, 0]];
[ [ 0, 1, 1 ], [ 0, 0, 1 ], [ 0, 0, 0 ] ]
gap> D := DigraphByAdjacencyMatrix(mat);
For a simple way of finding the shortest path between two specific vertices,
see <Ref Oper="DigraphShortestPath"/>. See also the weighted operation
<Ref Oper="EdgeWeightedDigraphShortestPath"/>.
<Example><![CDATA[
gap> D := Digraph([[2, 3], [3], []]);
<immutable digraph with 3 vertices, 3 edges>
gap> DigraphDijkstra(D, 2, 3);
[ [ infinity, 0, 1 ], [ -1, -1, 2 ] ]
gap> DigraphDijkstra(D, 1, 3);
[ [ 0, 1, 1 ], [ -1, 1, 1 ] ]
gap> DigraphDijkstra(D, 1, 2);
gap> DigraphShortestPaths(D, 1);
[ [ 0, 1, 1 ], [ -1, 1, 1 ] ]
gap> DigraphShortestPaths(D, 2);
[ [ infinity, 0, 1 ], [ -1, -1, 2 ] ]
]]></Example>
</Description>
</ManSection>
<#/GAPDoc>

<#GAPDoc Label="DigraphDijkstra">
<ManSection>
<Oper Name="DigraphDijkstra" Arg="digraph, source" Label="for a source"/>
<Returns>Two lists.</Returns>
<Description>
This is an obsolete synonym for
<Ref Oper="DigraphShortestPaths"/> and will
be removed in a future version.
</Description>
</ManSection>
<#/GAPDoc>

<#GAPDoc Label="ModularProduct">
<ManSection>
<Oper Name="ModularProduct" Arg="D1, D2"/>
Expand Down
1 change: 1 addition & 0 deletions doc/z-chap4.xml
Original file line number Diff line number Diff line change
Expand Up @@ -91,6 +91,7 @@
<#Include Label="DigraphDegeneracyOrdering">
<#Include Label="HamiltonianPath">
<#Include Label="NrSpanningTrees">
<#Include Label="DigraphShortestPaths">
<#Include Label="DigraphDijkstra">
<#Include Label="DigraphVertexConnectivity">
<#Include Label="DigraphEdgeConnectivity">
Expand Down
4 changes: 3 additions & 1 deletion gap/obsolete.gi
Original file line number Diff line number Diff line change
Expand Up @@ -13,4 +13,6 @@ function(oldname, func)
Info(InfoWarning, 1, "use \"", NameFunction(func), "\" instead");
return CallFuncList(func, arg);
end);
end);
end);

DIGRAPHS_DeclareObsoleteSynonym("DigraphDijkstra", DigraphShortestPaths);
6 changes: 2 additions & 4 deletions gap/oper.gd
Original file line number Diff line number Diff line change
Expand Up @@ -129,10 +129,6 @@ DeclareOperation("DigraphKings", [IsDigraph, IsPosInt]);

DeclareOperation("DigraphFloydWarshall",
[IsDigraph, IsFunction, IsObject, IsObject]);
DeclareOperation("DigraphDijkstra",
[IsDigraph, IsPosInt]);
DeclareOperation("DigraphDijkstra",
[IsDigraph, IsPosInt, IsPosInt]);

DeclareOperation("DigraphConnectedComponent", [IsDigraph, IsPosInt]);
DeclareOperation("DigraphStronglyConnectedComponent", [IsDigraph, IsPosInt]);
Expand All @@ -151,7 +147,9 @@ DeclareOperation("DigraphDistanceSet", [IsDigraph, IsPosInt, IsList]);
DeclareOperation("DigraphShortestDistance", [IsDigraph, IsPosInt, IsPosInt]);
DeclareOperation("DigraphShortestDistance", [IsDigraph, IsList, IsList]);
DeclareOperation("DigraphShortestDistance", [IsDigraph, IsList]);
DeclareGlobalFunction("DIGRAPHS_ShortestPathsBFS");
DeclareOperation("DigraphShortestPath", [IsDigraph, IsPosInt, IsPosInt]);
DeclareOperation("DigraphShortestPaths", [IsDigraph, IsPosInt]);
DeclareOperation("DigraphShortestPathSpanningTree", [IsDigraph, IsPosInt]);
DeclareOperation("VerticesReachableFrom", [IsDigraph, IsPosInt]);
DeclareOperation("VerticesReachableFrom", [IsDigraph, IsList]);
Expand Down
162 changes: 77 additions & 85 deletions gap/oper.gi
Original file line number Diff line number Diff line change
Expand Up @@ -1806,19 +1806,53 @@ function(D, nodes, edges)
return true;
end);

# BFS search from source vertex outwards. if target is not 'fail' then stops
# as soon as it is found. returns two lists; for each vertex, the index v is:
# - distance from source vertex
# - previous vertex on shortest path from source
InstallGlobalFunction(DIGRAPHS_ShortestPathsBFS,
function(neighbours, source, target)
local dist, previous, queue, i, a, b;

dist := ListWithIdenticalEntries(Length(neighbours), infinity);
previous := ListWithIdenticalEntries(Length(neighbours), -1);

dist[source] := 0;
queue := [source];
i := 1;
while i <= Length(queue) do
a := queue[i];
i := i + 1;
for b in neighbours[a] do
if dist[b] = infinity then
dist[b] := dist[a] + 1;
previous[b] := a;
if b = target then
return [dist, previous];
fi;
Add(queue, b);
fi;
od;
od;
return [dist, previous];
end);

InstallMethod(DigraphShortestPath,
"for a digraph by out-neighbours and two pos ints",
[IsDigraphByOutNeighboursRep, IsPosInt, IsPosInt],
"for a digraph and two vertices",
[IsDigraph, IsPosInt, IsPosInt],
function(D, u, v)
local current, next, parent, distance, falselist, verts, nbs, path, edge,
n, a, b, i;
local verts, reversed, a, distanceto, neighbours, vertices, edges, best, w, i;

verts := DigraphVertices(D);
if not (u in verts and v in verts) then
ErrorNoReturn("the 2nd and 3rd arguments <u> and <v> must be ",
"vertices of the 1st argument <D>,");
fi;

if u = v then
return fail;
fi;

if IsDigraphEdge(D, u, v) then
return [[u, v], [Position(OutNeighboursOfVertex(D, u), v)]];
elif HasIsTransitiveDigraph(D) and IsTransitiveDigraph(D) then
Expand All @@ -1831,98 +1865,56 @@ function(D, u, v)
return fail;
fi;

nbs := OutNeighbours(D);
distance := ListWithIdenticalEntries(Length(verts), -1);

# Setting up objects useful in the function.
parent := [];
current := [u];
edge := [];
next := BlistList([1 .. Length(verts)], []);
falselist := BlistList([1 .. Length(verts)], []);

n := 0;
while current <> [] do
n := n + 1;
for a in current do
for i in [1 .. Length(nbs[a])] do
b := nbs[a][i];
if distance[b] = -1 then
distance[b] := n;
next[b] := true;
parent[b] := a;
edge[b] := i;
fi;
# the rest of this method is to guarantee that the returned path is lex-least
# otherwise could generate path by just walking backwards via predecessors

if b = v then
path := [[], []];
# Finds the path
for i in [1 .. n] do
Add(path[1], b);
Add(path[2], edge[b]);
b := parent[b];
od;
Add(path[1], u); # Adds the starting vertex to the list of vertices
return [Reversed(path[1]), Reversed(path[2])];
fi;
od;
od;
current := ListBlist(verts, next);
IntersectBlist(next, falselist);
# want to walk forwards from u to v, which requires knowing the distance to
# v instead of from u, therefore have to call the BFS on the reverse of D
# could use DigraphReverse(), but if D is mutable it gets changed in place,
# so would have to be un-reversed afterwards
neighbours := OutNeighbours(D);
reversed := List([1 .. Length(neighbours)], x -> []);
for a in [1 .. Length(neighbours)] do
for w in neighbours[a] do
Add(reversed[w], a);
od;
od;
distanceto := DIGRAPHS_ShortestPathsBFS(reversed, v, u)[1];
if distanceto[u] = infinity then
return fail;
end);

BindGlobal("DIGRAPHS_DijkstraST",
function(digraph, source, target)
local dist, prev, queue, u, v, alt;

if not source in DigraphVertices(digraph) then
ErrorNoReturn("the 2nd argument <source> must be a vertex of the ",
"1st argument <digraph>");
elif target <> fail and not target in DigraphVertices(digraph) then
ErrorNoReturn("the 3rd argument <target> must be a vertex of the ",
"1st argument <digraph>");
fi;

dist := [];
prev := [];
queue := BinaryHeap({x, y} -> x[1] < y[1]);

for v in DigraphVertices(digraph) do
dist[v] := infinity;
prev[v] := -1;
od;

dist[source] := 0;
Push(queue, [0, source]);

while not IsEmpty(queue) do
u := Pop(queue);
u := u[2];
# TODO: this has a small performance impact for DigraphDijkstraS,
# but do we care?
if u = target then
return [dist, prev];
fi;
for v in OutNeighbours(digraph)[u] do
alt := dist[u] + DigraphEdgeLabel(digraph, u, v);
if alt < dist[v] then
dist[v] := alt;
prev[v] := u;
Push(queue, [dist[v], v]);
vertices := [u];
edges := [];
a := u;
while a <> v do
best := fail;
# find smallest vertex that brings us one step closer to v
# OutNeighbours aren't necessarily in order, so is slightly more involved
for i in [1 .. Length(neighbours[a])] do
w := neighbours[a][i];
if distanceto[w] = distanceto[a] - 1
and (best = fail or w < neighbours[a][best]) then
best := i;
fi;
od;
Add(edges, best);
a := neighbours[a][best];
Add(vertices, a);
od;
return [dist, prev];
return [vertices, edges];
end);

InstallMethod(DigraphDijkstra, "for a digraph, a vertex, and a vertex",
[IsDigraph, IsPosInt, IsPosInt], DIGRAPHS_DijkstraST);

InstallMethod(DigraphDijkstra, "for a digraph, and a vertex",
InstallMethod(DigraphShortestPaths, "for a digraph and a vertex",
[IsDigraph, IsPosInt],
{digraph, source} -> DIGRAPHS_DijkstraST(digraph, source, fail));
function(D, source)
if not source in DigraphVertices(D) then
ErrorNoReturn("the 2nd argument <source> must be a vertex of the ",
"1st argument <D>");
fi;

return DIGRAPHS_ShortestPathsBFS(OutNeighbours(D), source, fail);
end);

InstallMethod(IteratorOfPaths,
"for a digraph by out-neighbours and two pos ints",
Expand Down
Loading
Loading