educative.io

Is visited array necessary here?

Is the visited array here necessary? Is it to guard against cycles in the graph or is it an optimization?

 private fun findPath(graph: Map<Int, IntArray>, start: Int, end: Int): Boolean {
        if (start == end) {
            return true
        }

        val children = graph.getOrDefault(start, intArrayOf())

        children.forEach {
            return findPath(graph, it, end)
        }

        return false
    }

You’re right there. This visited array is used to guard against cycles. Otherwise, it’ll keep roaming around an infinite loop. This visited array acts as checklist.