Please debugg my code my code is not passing test cases

Are you facing wrong answer or TLE in test cases?

wrong answer pls debugg

Your dfs and issafe() function is not understandable to me. But the implementation you have used is right for sure. I would suggest you to post another doubt as another TA will help you for better debugging.Though you can take this code for reference