I have this function at the moment
def isConnected(adjacencyListMap: Map[String, Seq[String]]): Boolean = {
// Simple BFS to check whether each vertex is connected
val visitedMap = mutable
.Map[String, Boolean]() ++= adjacencyListMap.keys.map(vertex => vertex -> false).toMap
val seen = mutable.Stack[String]()
seen.push(adjacencyListMap.keys.head)
while (seen.nonEmpty) {
val v = seen.pop()
visitedMap.put(v, true)
val adjacentVertices = adjacencyListMap(v)
adjacentVertices.foreach(adjVertex => {
if (!visitedMap(adjVertex)) {
visitedMap.put(adjVertex, true)
seen.push(adjVertex)
}
})
}
// If all vertices are visited then we know all vertices are connected in 1 component
visitedMap.values.reduce(_ && _)
}
The function in essence takes in a Map where each vertex is a key and all adjacent vertices to that vertex are values. We basically do a BFS and at the end check whether all vertices were visited, if they were then we know that graph is one component and connected, if not then it is not connected.
How would I go about making this code more immutable (i.e. the mutable seen
Stack and mutable visitedMap
HashMap)?