I have tried appending '\0' to each row before,but it didn't help either.So,I think,the column has something wrong only in this problem.I have written some similar codes in many other problems(with column),and it has been accepted.I have given up.
@xiaoyu.bai I know this is late but I just resolved the same problem from BFS. I got TLE because I didn't mark squares that are already in the queue as visited (using another symbol). Thus, some squares got re-added to the queue and wasted run-time and memory. DFS does not have the same problem since the algorithm mostly travels in one direction until it reaches the border.