Thank you for the excellent solution. It's the most clear one I think.
But I still have one more question:
Is there any protection from the 'out of range' in your code?
I mean, when we come to
chances are there that (i,j) is out of the forest, right?