Given a n*mSuppose we are given an $n\times m$ matrix, M $M$ of positive integers. Here, theThe adjacent cells of a particular cell is the up, down, left and right cells. Like for cell M[i][j]$M[i][j]$ the adjacent cells are M[i-1][j]$M[i-1][j]$, M[i+1][j]$M[i+1][j]$, M[i][j-1]$M[i][j-1]$ and M[i][j+1]$M[i][j+1]$ respectively.
An area is a set of cells such that for each pair of cells $(u_0,v)$ in the area, there is a sequence of cells $u_1,\ldots,u_k$ in the area such that $u_{i+1}$ is an adjacent cell of $u_i$ and $u_k$ is an adjacent cell of $v$. The problem is to find out a maximum area (i.e. an area with maximum number of adjacent cells) of this matrix which contains exactly two different numbers.
For an example: M = \begin{bmatrix}5&3&2&5&5\\2&1&2&5&3\\6&1&5&2&5\\5&2&5&3&5\\4&6&8&9&6\end{bmatrix}$$M=\begin{bmatrix}5&3&2&5&5\\2&1&2&5&3\\6&1&5&2&5\\5&2&5&3&5\\4&6&8&9&6\end{bmatrix},$$ Here the maximum area contains 10 cells. And the area is: \begin{bmatrix}*&*&2&5&5\\*&*&2&5&*\\*&*&5&2&*\\5&2&5&*&*\\*&*&*&*&*\end{bmatrix}$$\begin{bmatrix}*&*&2&5&5\\*&*&2&5&*\\*&*&5&2&*\\5&2&5&*&*\\*&*&*&*&*\end{bmatrix}.$$ What is the most efficient way to find the maximum area?