Scala Graph Cycle Detection Algo 'return' needed?

前端 未结 5 1087
你的背包
你的背包 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:05

    Answer added just to show that the mutable-visited isn't too unreadable either (untested, though!)

    def isCyclic() : Boolean =
    {
         var visited = HashSet()
    
         def hasCycle(node:Node) = {
            if (visited.contains(node)) {
               true
            } else {
               visited :+= node
               children(node).exists(hasCycle(_))
            }
        }
        nodes.exists(hasCycle(_))
    }
    
    def children(node:Node) = vertexMap.getChildren(node.id).toList.map(nodeId => id2nodeMap(nodeId))
    

提交回复
热议问题