TLE in BFS-Shortest Path

I am getting TLE in BFS-Shortes Path on Hacker Blocks. link to the problem : https://hack.codingblocks.com/contests/c/537/763

Link to my code is: https://paste.ofcode.org/aKHVsMeF8RtQTvKUmmymRT

Please help me by suggesting how can I modify my solution to get it accepted.
Thanks.

Hey Kaushal, there is just a small change in the body of your if check (line 42) of your code i.e. if you are visiting a node for the first time them mark it as visited.

if(!visited[i])
      {   visited[i]=1;  
          distance[i] = distance[node] + 1;
          q.push(i);
      }
1 Like

Thank you very much.