So I am a newbie in DFS and BFS, and was solving this problem. Surprisingly, giving TLE in 3rd testcase. I can't seem to understand where code is inefficient since time complexity is looking fine to me.
I have added some comments, which don't use the ideal terminologies but would hopefully convey what I'm trying to do