X Interview Question

The problem is a quite usual one with BFS algorithm.