TLE in Testcase 1,3,4

I have followed the approach in the hint videos.
Can you see where to optimize my code and how.

Question:
https://online.codingblocks.com/app/player/65729/content/108580/5265/code-challenge

Solution:

@Abhishek.1514 Your logic is correct but time complexity of your code is little bit high.

your visited is a map, which have increased time complexity of your code by factor log(N*M). Change it to bool [1005][1005] and try implementing using it.