I want to know whether an edge exist between two specific vertex? Is there any function like EdgeExist[g,{v1,v2}]?
1 Answer
Yes, there is EdgeQ:
g = Graph[{1 -> 2, 2 -> 3, 3 -> 1}, VertexShapeFunction -> "Name"]
{EdgeQ[g, 1 -> 2], EdgeQ[g, DirectedEdge[1, 2]],
EdgeQ[g, 1 <-> 2], EdgeQ[g, UndirectedEdge[1, 2]],
EdgeQ[g, 2 -> 1], EdgeQ[g, DirectedEdge[2, 1]]}
{True, True, False, False, False, False}
If you need a function that takes a list of (unordered) vertices as the second arguments, you can use
edgeQ[g_, e : {_, _}] := Or @@ (EdgeQ[g, #] & /@ {DirectedEdge @@ e,
DirectedEdge @@ Reverse[e], UndirectedEdge @@ e})
edgeQ[g, {1, 2}]
True
If the ordering is important, remove DirectedEdge @@ Reverse[e]
from the function definition.
Notes: As @Szabolcs noted in the comments, a <-> b
is equivalent to UndirectedEdge
, but a -> b
is not the same as DirectedEdge
. a -> b
is treated as DirectedEdge
only in a directed graph; in an undirected or mixed graph it is treated as UndirectedEdge
.
-
$\begingroup$ It would be good to mention the non-obvious property that
UndirectedEdge[a,b]
(same asa <-> b
) tests for an undirected edge only (but not directed),DirectedEdge[a,b]
tests for a directed edge only (but not undirected) andRule[a, b]
(same asa -> b
and different fromDirectedEdge[a,b]
) test for either/both. This is important when it is not known beforehand if the graph is directed or if working with mixed graphs. Oh, and this important property is of course not documented ... $\endgroup$– SzabolcsMay 1, 2016 at 13:50 -
$\begingroup$ The way the answer is phrased now seems to imply that
->
represents a directed edge but it doesn't ... it could also be undirected. $\endgroup$– SzabolcsMay 1, 2016 at 13:51 -
1$\begingroup$ Hm, actually I was wrong and it turns out that in mixed graphs
->
is interpreted as strictly undirected. In directed ones it's interpreted as directed and in undirected ones it's interpreted as undirected. $\endgroup$– SzabolcsMay 1, 2016 at 13:53 -
$\begingroup$ @Szabolcs, good points, I added a note covering your observations. $\endgroup$– kglrMay 1, 2016 at 14:01
-
$\begingroup$ @Szabolcs, thank you for the edit. (I still use version 9, so could not use a mixed graph to check how it works with different forms of the second argument.) $\endgroup$– kglrMay 1, 2016 at 14:09