Algorithm

Jump Game IV

Solution
# when current layer exists
        while curs:
            nex = []
            # iterate the layer
            for node in curs:
                # check if reached end
                if node == n-1:
                    return step
                # check same value
                for child in graph[arr[node]]:
                    if child not in visited:
                        visited.add(child)
                        nex.append(child)
                # clear the list to prevent redundant search
                graph[arr[node]].clear()
                # check neighbors
                for child in [node-1, node+1]:
                    if 0 <= child < n and child not in visited:
                        visited.add(child)
                        nex.append(child)
            curs = nex
            step += 1
        return -1