Create an $N$ by $M$ grid with numbers in such a way that satisfies following conditions:

1. numbers should be integers that range from $1$ to $r$.
2. for any cell $C$, all its adjacent neighbors (i.e. bottom, top, left, right cells) must have different values.
3. $r$ must be minimal.

For example, a solution for a $3$ by $3$ grid is...

$\begin{bmatrix}1 & 2 & 2\\1 & 3 & 4\\2 & 3 & 1\end{bmatrix}$

In this case, $r = 4$.