Scala Graph Cycle Detection Algo 'return' needed?

前端 未结 5 1093
你的背包
你的背包 2020-12-18 12:35

I have implemented a small cycle detection algorithm for a DAG in Scala. The \'return\' bothers me - I\'d like to have a version without the return...possible?



        
5条回答
  •  渐次进展
    2020-12-18 13:08

    I think the problem can be solved without changing the state of the node with the marker field. The following is a rough code of what i think the isCyclic should look like. I am currently storing the node objects which are visited instead you can store the node ids if the node doesnt have equality based on node id.

    def isCyclic() : Boolean = nodes.exists(hasCycle(_, HashSet()))
    
    def hasCycle(node:Node, visited:Seq[Node]) = visited.contains(node) || children(node).exists(hasCycle(_,  node +: visited))
    
    
    def children(node:Node) = vertexMap.getChildren(node.id).toList.map(nodeId => id2nodeMap(nodeId))
    

提交回复
热议问题