Don't forget to border the input field with sentinels in order to simplify the implementation reducing the number of conditions to check. This is done embedding the mxn input field into a (m+2)x(n+2) array.