Speeded up the algorithm with a queue.