I dont know if anyone came up with this soln but when I thought of this soln I got extremely happy and joyful. Here goes the logic: Basically we can use dfs to iterate through every node and use a dp table which holds the maximum distance of that node from the end node(n). Now the base case will be when we reach 'n' we return 1. Now for every other node we call dfs for all its adjacent nodes and return the value of that node as maximum of all the distances the adjacent node returns. At the same time we hold a child vector which stores the next node for each node. We do this in order to be able to trace the path. However, if we dont reach n we return 0. So that's the "IMPOSSIBLE" condition. So, dp[i] shows the max distance of that node from 'n'