Changed data structure for efficiency. Use deque and set, dictionary.