Editorial for Pursuit of Knowledge
Submitting an official solution before solving the problem yourself is a bannable offence.
If you tried to run a BFS for each query, it is likely your code would've failed(unless it was in c++ or PYPY2 with good optimization). This is because the time cost is Q(N+M), where Q is a ridiculously huge number. Notice that there are many more queries than possible source nodes. Therefore, all we need to do is run BFS from each possible source node and store the values in an answer array. For each query, just grab the value from the answer array. In total, this solution takes N(N+M) time, a significant upgrade from the first.
Skills needed: BFS
Time complexity: O(N(N+M)+Q)
Note: The difficulty curve from J4 and J5 is quite steep. This question requires an algorithm known as Breadth First Search, which you can search up online.