0

I've seen the following code to traverse a graph depth first, in Scala:

def dfs(node: Node, seen: Set[Node]) = {
    visit(node)
    node.neighbours.filterNot(seen).foreach(neighbour => dfs(node, seen + node))
}

It seems to me this code is not correct as shown with the following example.

Nodes are 1, 2, 3. Edges are 1 -> 3, 1 -> 2, 2 -> 3

dfs(1, Set.empty) would visit node 1, then node 3, then node 2, then node 3 again because we don't maintain a global Set of seen nodes, but only add them in the recursive call to dfs.

What would instead be a correct implementation of DFS in Scala, without using mutable structures?

3

1 Answer 1

0

Something like this should work (though you might consider the foldLeft to be cheating a little):

def dfs(node: Node): Set[Node] = {
  def helper(parent: Node, seen: Set[Node]): Set[Node] = {
    neighbors(parent).foldLeft(seen)({ case (nowSeen, child) =>
      if (nowSeen.contains(child)) nowSeen else {
        visit(child)
        helper(child, nowSeen + child)
      }
    })        
  }

  visit(node)
  helper(node, Set(node)) 
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.