Recently, I have come across a problem that need to find a path from $$$S$$$ to $$$T$$$ like these :

I have tried to do a dfs with order like: up (-1, 0) , right (0, 1), down (1, 0), left(0, -1) (Suppose $$$S$$$ is (1, 1) and $$$T$$$ is (n, m) ). However it fails cases like this

I tried to google it too (but don't know how to use which words to describe this so fail finding anything.). I wonder if there is any algorithm for this.

Thanks anyway <3