Labyrinth Cses set | help needed | TLE

I am getting TLE in this question. Can somebody help me to correct my code?
Problem:CSES - Labyrinth
My Solution:https://cses.fi/paste/9835aecc6fe574344034b6/

I am very confused about your code. But I will try to point out what is looking wrong to me:

while (!q.empty())
{
     int sz = q.size();
     while (sz--)
     {
         ...
     }
}

you run a while-loop until q is empty and inside that while loop, you run another while-loop until q is empty. Having 2 while loops like that is horribly unnecessary.

using a queue looks perfect. But you kind of fail to realize why. If you start at A and push all valid neighbors into the queue, then these will have a distance of 1 to A. In the next iteration, all valid and NOT visited neighbors will have a distance of 2 to A. In the next iteration the distance to A will be 3 and so on. You keep going until you either find B or no new neighbors.

^I don’t really understand if your printed path will be correct and fast enough. If it is not, I would create a 2d array and store the distance to A in each cell. Using your queue-approach, you can do that in O(n*m). Printing the correct path with the help of that 2d array can be done in O(distance) or O(n+m)