Query to check if there is a cycle in a graph with edges visited only once

无人久伴 提交于 2019-12-01 11:18:19

I was using the following sample graph:

g = TinkerGraph.open().traversal()
g.addV().property(id, 'blue').as('b').
  addV().property(id, 'orange').as('o').
  addV().property(id, 'red').as('r').
  addV().property(id, 'white').as('w').
  addE('bridge').from('w').to('b').
  addE('bridge').from('w').to('o').
  addE('bridge').from('w').to('r').
  addE('bridge').from('w').to('r').
  addE('bridge').from('o').to('b').
  addE('bridge').from('o').to('b').
  addE('bridge').from('o').to('r').
  addE('bridge').from('o').to('r').iterate()

The following query returns the first possible path:

gremlin> g.V().sideEffect(outE("bridge").aggregate("bridges")).barrier().
......1>   repeat(bothE().or(__.not(select('e')),
......2>                     __.not(filter(__.as('x').select(all, 'e').unfold().where(eq('x'))))).as('e').otherV()).
......3>     until(select(all, 'e').count(local).as("c").select("bridges").count(local).where(eq("c"))).limit(1).
......4>   path().by(id).by(constant(" -> ")).map {String.join("", it.get().objects())}
==>orange -> blue -> white -> orange -> red -> white -> red -> orange -> blue

If all you need is a boolean value, then just append .hasNext():

g.V().sideEffect(outE("bridge").aggregate("bridges")).barrier().
  repeat(bothE().or(__.not(select('e')),
                    __.not(filter(__.as('x').select(all, 'e').unfold().where(eq('x'))))).as('e').otherV()).
    until(select(all, 'e').count(local).as("c").select("bridges").count(local).where(eq("c"))).hasNext()
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!