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?